<?php
namespace app\model;



class Worker {

static function MyorderWorkerCheck($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $uid = intval($_P['uid']);
    $shopid = $myworker['company'];

    if ($system['ruanjian']==3 && $shopid==0){
        return array('tishi'=>2, 'msg' => "错误:您的员工状态不正确,请重新扫描【添加员工】的二维码" );
    }

    $sql = "SELECT * FROM " . tablename (t_record) . "
                                        WHERE themeid =:themeid
                                                and uid = :uid and status > 0 order by type asc limit 1";
    $order = db_find($sql, array(":themeid"=>$themeid,":uid"=>$uid));
    if(empty($order) ){
        return array('tishi'=>2, 'msg' => "错误:该客户还未付款" );
    }

    if ($config['shopstype5']==1) {
        $options = str_replace("|", "','",$order['option']);
        $tiaojian = " and name in ('" . $options ."')";
        $shoplist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
            " WHERE  state = 1 and id = '{$shopid}' " . $tiaojian . " order by displayorder" );
        if (empty($shoplist)) {
            return array('error' =>1 , 'msg' => "客户未选择您家核销，客户已选择：" . str_replace("|", ",",$order['option']));
        }
    }

    $shop=db_find("SELECT * FROM ".tablename(t_hexiao)." WHERE uid = '{$uid}' and shopid = '{$shopid}' and themeid = '{$themeid}'");
    if(!empty($shop) ){
        if ($shop['workerid']==-1){
            $hexiaoworker = array();
            $hexiaoworker['username']='后台';
        }else{
            $hexiaoworker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$shop['workerid']}'");
        }

        return  array('tishi'=>2,'msg' => '错误:已经于'.$shop['addtime'].'由本公司'.$hexiaoworker['username'].'核销过' );
    }else{
        $data ['uniacid'] = $_G['mpid'];
        $data ['uid'] = $uid;
        $data ['shopid'] = $shopid;
        $data ['themeid'] = $themeid;
        $data ['workerid'] = $_G['member']['uid'];
        $data ['addtime'] = date('Y-m-d H:i:s');
        db_insert ( t_hexiao, $data );
        return  array('tishi'=>1 );

    }
}
static function Myorder($system,$theme,$config,$fans,$themeid) {
    global $_P, $_G;
    $themyrecord = Record::getLastGroupByOpenId($_G['openid'],$themeid);
    if(!empty($themyrecord)){
        if ($themyrecord['type']==1){
            $recordid = $themyrecord['pid'];
        }else{
            $recordid = $themyrecord['id'];
            $isleader = 1;
        }
        $themyrecordid = $recordid+1000;
    }else{
        return array('error' =>1 , 'msg' => "未查到您的付款定单" );
    }

    //2扫公司码，//3扫员工码
    if ($_P['type']==2 || $_P['type']==3) {
        if ($_P['type']==2){
           $shopid=$_P['cid']; 
           $workerid=-2;
        }else{
            $workerid=$_P['cid']; 
            $hexiaoworker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE themeid = '{$themeid}' and  uid = '{$workerid}'");
            $shopid=$hexiaoworker['company'];
        }
        if (empty($shopid)) {
            $shangjia=db_find("SELECT * FROM ".tablename(t_shangjia));
            if (!empty($shangjia) && $system['ruanjian']==3) {
                return array('error' =>1 , 'msg' => "商家信息不正确" );
            }
        }else{
            $shangjia=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE  id = '{$shopid}'");  
            if (empty($shangjia) && $system['ruanjian']==3) {
                return array('error' =>1 , 'msg' => "商家信息不正确" );
            }
        }

        if ($config['shopstype5']==1) {
            $options = str_replace("|", "','",$themyrecord['option']);
            $tiaojian = " and name in ('" . $options ."')";
            $shoplist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
                " WHERE  state = 1 and id = '{$shopid}' " . $tiaojian . " order by displayorder" );
            if (empty($shoplist)) {
                return array('error' =>1 , 'msg' => "未选择此商家核销，您已选择：" . str_replace("|", ",",$themyrecord['option']));
            }
        }

        $shop=db_find("SELECT * FROM ".tablename(t_hexiao)." WHERE uid = '{$_G['member']['uid']}' and shopid = '{$shopid}' and themeid = '{$themeid}'");
        if(!empty($shop) ){
            if ($shop['workerid']==-1){
                $hexiaoworker = array();
                $hexiaoworker['username']='后台';
            }elseif ($shop['workerid']==-2){
                $hexiaoworker = array();
                $hexiaoworker['username']='【核销码】';
            }else{
                $hexiaoworker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE themeid = '{$themeid}' and  uid = '{$shop['workerid']}'");
            }
            $addtime = strtotime($shop['addtime']);
            if ($addtime> TIMESTAMP-60) {
                $hexiao = array('tishi'=>1,'msg' => "成功核销" );
            }else{
                $hexiao = array('tishi'=>2,'msg' => '错误:已经于'.$shop['addtime'].'由本公司'.$hexiaoworker['username'].'核销过' );
            }
        }else{
            $data ['uniacid'] = $_G['mpid'];
            $data ['uid'] = $_G['member']['uid'];
            $data ['shopid'] = $shopid;
            $data ['themeid'] = $themeid;
            $data ['workerid'] = $workerid;
            $data ['addtime'] = date('Y-m-d H:i:s');
            db_insert ( t_hexiao, $data );
            $hexiao = array('tishi'=>1,'msg' => "成功核销" );
        }
    }

    $showrecord = Record::getAttendGroupById($recordid);
    if (empty($showrecord)){
        $showrecord = $themyrecord;
    }
    $detaillist = Record::getDetailListByPid($recordid);

    $count = Record::getAttendDetailNumByPId($recordid);
    if ($showrecord['renshu'] == 1) {
        $maxcount = $config['maxcountall2']-1;
    }else{
        $maxcount = $config['maxcount'];
    }   
    $nowgroupneednum=max(0,$maxcount-$count);

    if ($showrecord['xunifinish']==1) {
        $kaishishu = $showrecord['uid'] % 500;
        $xunisql = "SELECT avatar,username FROM " . tablename('2019xuni_fans') . " where
             id >". $kaishishu ." limit ".$nowgroupneednum;
        $xunilist = db_select ( $xunisql );
        if (!empty($detaillist)) {
            $detaillist = array_merge($detaillist , $xunilist);
        }else{
            $detaillist = $xunilist;
        }

        $nowgroupneednum=0;
    }else{
        $num_arr = array();
        if ($config['maxcountall']<=20){
            for($i=0;$i<$nowgroupneednum;$i++){
                $num_arr[$i] = $i; 
            }
        }
    }

    $worker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$themyrecord['workerid']}'");

    $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$worker['company']}'");
    $shopname=$shop['name'];

    if ($config['shopstype5']==1) {
        $options = str_replace("|", "','",$themyrecord['option']);
        $tiaojian = " and name in ('" . $options ."')";
    }
    $shoplist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
            " WHERE  state = 1 " . $tiaojian . " order by displayorder" );

    if(!empty($shoplist)){
        foreach($shoplist as $k=>$item){

            $shop=db_find("SELECT addtime,workerid FROM ".tablename(t_hexiao)." WHERE uid = '{$_G['member']['uid']}' and shopid = '{$item['id']}' and themeid = '{$themeid}'");
            if (!empty($shop)) {
                if ($shop['workerid'] == '-1') {
                    $shoplist[$k]['workername'] = '后台手工核销';
                }elseif ($shop['workerid'] == '-2') {
                    $shoplist[$k]['workername'] = '客户扫码核销';
                }else{
                    $hexiaoworker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$shop['workerid']}'");
                    $shoplist[$k]['workername'] = "核销人：" . $hexiaoworker['username'];
                    $shoplist[$k]['workermobile'] = $hexiaoworker['mobile'];
                }
                $shoplist[$k]['addtime'] = $shop['addtime'];
            }
        }
    }else{
        $shop=db_find("SELECT addtime,workerid FROM ".tablename(t_hexiao)." WHERE  uid = '{$_G['member']['uid']}' and shopid = '0' and themeid = '{$themeid}'");

        if ($shop['workerid'] == '-1') {
            $shop['workername'] = '后台手工核销';
        }else{
            $hexiaoworker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$shop['workerid']}'");
            $shop['workername'] = $hexiaoworker['username'];
            $shop['workermobile'] = $hexiaoworker['mobile'];
        }
        $shop['addtime'] = $shop['addtime'];

        $shop['name'] = $theme['jubf'];
        $shoplist[0]= $shop;

    }
    $showtuan = array();
    $showtuan[0] = $showrecord['avatar'];
    foreach ($detaillist as $index => $item) {
       $showtuan[$index+1] = $item['avatar'];
    }
    if (!empty($fans['hexiaoerm']) ) {//&& ($fans['hexiaoermtime']+1296000) > TIMESTAMP
        $qrimg = $fans['hexiaoerm'] ;
    }else{
        //若海报未设置，则只返回二维码
        $scene = MODULE_NAME . "-" . $themeid . "-" . $_G['member']['uid'] . "-" . $theme['softkey'] . "-1" ;
        $qrimg = Poster::CreateScene($system,$scene,'pages/myorder/myorder');
        db_update(t_fans, array('hexiaoerm' =>$qrimg), array('uniacid' => $_G['mpid'], 'themeid' => $themeid, 'openid' => $_G['openid']));
    }

    $result = array(
        'config' =>  array(
            'title' =>$theme['title'] , 
            'recordtype' =>$showrecord['type'], 
            'maxcountall' => $config['maxcountall'], 
            'nowgroupneednum' => $nowgroupneednum, 
        ),
        'fans' =>  array(
            'avatar' => $fans['avatar'], 
            'nickname' => $fans['nickname'], 
            'username' => $themyrecord['username'], 
            'mobile' => $themyrecord['mobile'], 
            'shopname' => $shopname, 
            'qrimg' => $qrimg,
        ),
        'worker' =>  array(
            'username' => $worker['username'], 
            'mobile' => $worker['mobile'], 
        ),
        'shoplist' =>$shoplist,
        'showtuan'=>$showtuan,
        'num_arr'=>$num_arr,
        'hexiao'=>$hexiao,
    );
    return $result;
}
static function w_setmobile($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    if($myworker['level']!=1){
        return array('error' =>1 , 'msg' => "无权访问" );
    }

    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $id = intval($_P['id']);
    if ($op=='display') {

        $confignew = array(            
            "ruanjian" =>$system['ruanjian'],
            "workerpass" =>$config['workerpass'],
            "iseditorder" =>$config['iseditorder'],
            "isreport" =>$config['isreport'],
            "isrank" =>$config['isrank'],
            "isshoprank" =>$config['isshoprank'],
            "isxianxia" =>$config['isxianxia'],
            "isexampleqr" =>$config['isexampleqr'],
            "examplestyle" =>$config['examplestyle'],
        );
        $result = array(
            'config' => $confignew,
        );

    }elseif ($op=='save'){
    $config_old = $config;
    
    $config['workerpass'] = $_P['workerpass'];
    $config['isreport'] = intval($_P['isreport']);
    $config['isrank'] = intval($_P['isrank']);
    $config['isshoprank'] = intval($_P['isshoprank']);
    $config['isxianxia'] = intval($_P['isxianxia']);
    $config['isshowxianxia'] = intval($_P['isshowxianxia']);
    $config['iseditorder'] = intval($_P['iseditorder']);
    $config['isexampleqr'] = intval($_P['isexampleqr']);
    $config['examplestyle'] = intval($_P['examplestyle']);
    
    writelog($id,'手机编辑',$config_old,$config,$myworker['username']);
    Theme::setConfig($config,$themeid,$_G['mpid']);
    }
    return $result;
}  

static function w_setother($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    if($myworker['level']!=1){
        return array('error' =>1 , 'msg' => "无权访问" );
    }

    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $id = intval($_P['id']);
    if ($op=='display') {

        $confignew = array(
            "ruanjian" =>$system['ruanjian'],   
            "blacklist" =>$theme['blacklist'],
            "maxcountall" =>$config['maxcountall'],
            "tuanrank" =>$config['tuanrank'],
            "fansrank" =>$config['fansrank'],
            "sharetitlexcx" =>$config['sharetitlexcx'],
            "sharetitlexcx2" =>$config['sharetitlexcx2'],
        );

        $radio = array(            
            "isworkerpay" =>$config['isworkerpay'],
            "ishexiao" =>$config['ishexiao'],
            "isshowkefu" =>$config['isshowkefu'],
            "istime" =>$config['istime'],
            "iswttouxiang" =>$config['iswttouxiang'],
            "isshowname" =>$config['isshowname'],
            "showpayresult" =>$config['showpayresult'],
            "homeshowshop" =>$config['homeshowshop'],            
            "isdanmu" =>$config['isdanmu'],
            "danmu01" =>$config['danmu01'],
            "danmu02" =>$config['danmu02'],
            "danmu03" =>$config['danmu03'],
            "danmu04" =>$config['danmu04'],
        );
        $result = array(
            'config' => $confignew,
            'radio' => $radio,
        );

    }elseif ($op=='save'){
        $data = array (
            'blacklist'       => $_P['blacklist'],
        );
        Theme::update($themeid,$data);

        $theme_old = array(
            'blacklist'       => $theme ['blacklist'],
        );
        writelog($id,'手机编辑',$theme_old,$data,$myworker['username']);
        $config_old = $config;
        
        $config['isworkerpay'] = intval($_P['isworkerpay']);
        $config['ishexiao'] = intval($_P['ishexiao']);
        $config['homeshowshop'] = intval($_P['homeshowshop']);
        $config['tuanrank'] = intval($_P['tuanrank']);
        $config['fansrank'] = intval($_P['fansrank']);
        $config['sharetitle1'] = empty($_P['sharetitle1'])?$config['sharetitle1']:$_P['sharetitle1'];
        $config['sharetitle2'] = empty($_P['sharetitle2'])?$config['sharetitle2']:$_P['sharetitle2'];
        $config['sharetitlexcx'] = empty($_P['sharetitlexcx'])?$config['sharetitlexcx']:$_P['sharetitlexcx'];
        $config['sharetitlexcx2'] = empty($_P['sharetitlexcx2'])?$config['sharetitlexcx2']:$_P['sharetitlexcx2'];
        $config['isshowkefu'] = intval($_P['isshowkefu']);
        $config['istime'] = intval($_P['istime']);
        $config['iswttouxiang'] = intval($_P['iswttouxiang']);
        $config['isshowname'] = intval($_P['isshowname']);
        $config['showpayresult'] = intval($_P['showpayresult']);
        $config['isdanmu'] = intval($_P['isdanmu']);
        $config['danmu01'] = intval($_P['danmu01']);
        $config['danmu02'] = intval($_P['danmu02']);
        $config['danmu03'] = intval($_P['danmu03']);
        $config['danmu04'] = intval($_P['danmu04']);

        writelog($id,'手机编辑',$config_old,$config,$myworker['username']);
        Theme::setConfig($config,$themeid,$_G['mpid']);
        // return_msg('更新成功','','success');
    }


    return $result;
}



static function w_setxuni($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    if($myworker['level']!=1){
        return array('error' =>1 , 'msg' => "无权访问" );
    }

    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $id = intval($_P['id']);
    if ($op=='display') {
        if ($system['ruanjian']==0 && $system['softstyle']==5) {
            $total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
            $tiaojian =" WHERE recordid=99999 ";
            $total = db_fetchcolumn('SELECT COUNT(*) FROM ' .tablename(t_shengshi)."  {$tiaojian}");
            $totalsum = $total1  + $total;
        }elseif ($system['ruanjian']==3 && $system['softstyle']==2) {
            $total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
            $totalsum = $total1 ;
        }else{
            $total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
            $totalsum = $total1;

        }
        $scannum = Record::getscannumByThemeId($themeid,$config['showalldata']);

        // if ($system['softstyle']==7 || $system['ruanjian']==1){
        //  $groupsnum =intval($theme['forward']);
        // }else{
            $groupsnum = Record::getFansNumByThemeId($themeid,$config['showalldata']);
        // }

        $tuannum = Record::getGroupsNumByThemeId($themeid,$config['showalldata']);
        if($config['iscomm']==1 && $system['fenxiao07']==1){
            $commyaoyiyaofee = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " ))); 

            $commyaoyiyao = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " ); 
            $commyaoyiyao = $commyaoyiyao ;
            $commyaoyiyaofee = sprintf("%.2f",$commyaoyiyaofee );
            $yaoyiyao=true;
        }else{
            $yaoyiyao=false;
        }

        $confignew = array(
            "yaoyiyao" =>$yaoyiyao,

            "totalsum" =>$totalsum,
            "groupsnum" =>$groupsnum,
            "scannum" =>$scannum,
            "commyaoyiyao" =>$commyaoyiyao,
            "commyaoyiyaofee" =>$commyaoyiyaofee,

            "touxiang" =>$config['touxiang'],
            "fakejoin" =>$config['fakejoin'],
            "faketuan" =>$config['faketuan'],
            "fakescan" =>$config['fakescan'],
            "comm7num" =>$config['comm7num'],
            "comm7fee" =>$config['comm7fee'],
        );
        $result = array(
            'config' => $confignew,
        );

    }elseif ($op=='save'){
        $config_old = $config;
        
        $config['touxiang'] = intval($_P['touxiang']);
        $config['fakejoin'] = intval($_P['fakejoin']);
        $config['faketuan'] = intval($_P['faketuan']);
        $config['fakescan'] = intval($_P['fakescan']);
        $config['comm7num'] = intval($_P['comm7num']);
        $config['comm7fee'] = intval($_P['comm7fee']);

        writelog($id,'手机编辑',$config_old,$config,$myworker['username']);
        Theme::setConfig($config,$themeid,$_G['mpid']);
    }


    return $result;
}

static function w_setbase($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    if($myworker['level']!=1){
        return array('error' =>1 , 'msg' => "无权访问" );
    }

    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $id = intval($_P['id']);

    if ($op=='save'){

        if (empty($_P['title'])) {
            return array('error' =>1 , 'msg' => "活动主标题不可为空" );
        }

        $words=explode(",",$system['s']['adkeyword']);
        $res_banned1=Poster::check_words($words,$_P['title']);
        if (!empty($res_banned1)) {
            return array('error' =>1 , 'msg' => '主标题含有违规词：'.implode(',',$res_banned1) );
        }
        $res_banned2=Poster::check_words($words,$_P['desc']);
        if (!empty($res_banned2)) {
            return array('error' =>1 , 'msg' => '副标题含有违规词：'.implode(',',$res_banned2) );

        }

        $data = array (
            'title'       => $_P['title'],
            'desc'        => empty($_P['desc'])?$theme ['desc']:$_P['desc'],
            'mobile'      => $_P['mobile'],
            'endtime'     => strtotime($_P['endtime'])+59,
            'status'      => intval($_P['status']),
        );
        $theme_old = array(
            'title'       => $theme ['title'],
            'desc'        => $theme ['desc'],
            'mobile'      => $theme ['mobile'],
            'endtime'     => $theme ['endtime'],
            'status'      => $theme ['status'],
        );
        writelog($id,'手机编辑',$theme_old,$data,$myworker['username']);
        Theme::update($themeid,$data);
        $config_old = $config;

        $config['joinfee'] = sprintf("%.2f",floatval($_P['joinfee']));
        $config['renshu'] = intval($_P['renshu']);


        $config['groupprice'] = sprintf("%.2f",floatval($_P['groupprice']));
        $config['primeprice'] = sprintf("%.2f",floatval($_P['primeprice']));
        $config['marketprice'] = sprintf("%.2f",floatval($_P['marketprice']));
        $config['groupprice'] = sprintf("%.2f",floatval($_P['groupprice']));
        $config['groupprice2'] = sprintf("%.2f",floatval($_P['groupprice2']));
        $config['joinfee2'] = sprintf("%.2f",floatval($_P['joinfee2']));
        $config['joinfee3'] = sprintf("%.2f",floatval($_P['joinfee3']));

        $config['duojiagetips'] = $_P['duojiagetips'];
        $config['joinname'] = $_P['joinname'];
        $config['joinname2'] = $_P['joinname2'];
        $config['joinname3'] = $_P['joinname3'];
        $config['maxcountall'] = intval($_P['maxcountall']);
        $config['maxcountall2'] = intval($_P['maxcountall2']);
        $config['tuanmode'] = intval($_P['tuanmode']);
        $config['addresstxt'] = $_P['addresstxt'];
        $config['zhuandantxt'] = $_P['zhuandantxt'];
        $config['zhuandanbegintime'] = strtotime($_P['zhuandanbegintime']);
        $config['zhuandanendtime'] = strtotime($_P['zhuandanendtime']);
        $config['zhuandantips'] = $_P['zhuandantips'];

        writelog($id,'手机编辑',$config_old,$config,$myworker['username']);
        Theme::setConfig($config,$themeid,$_G['mpid']);
    }

    $systemnew = array(
        'ruanjian' => $system['ruanjian'],
        'softstyle' => $system['softstyle'],
        'jiage' => $system['jiage'],
        'softstyle' => $system['softstyle'],

    );
    $confignew = array(
        "joinfee" =>$config['joinfee'],
        "renshu" =>$config['renshu'],
        "groupprice" =>$config['groupprice'],
        "primeprice" =>$config['primeprice'],
        "marketprice" =>$config['marketprice'],
        "groupprice" =>$config['groupprice'],
        "groupprice2" =>$config['groupprice2'],
        "joinfee2" =>$config['joinfee2'],
        "joinfee3" =>$config['joinfee3'],
        "duojiagetips" =>$config['duojiagetips'],
        "joinname" =>$config['joinname'],
        "joinname2" =>$config['joinname2'],
        "joinname3" =>$config['joinname3'],
        "maxcountall" =>$config['maxcountall'],
        "maxcountall2" =>$config['maxcountall2'],
        "tuanmode" =>$config['tuanmode'],
        "addresstxt" =>$config['addresstxt'],
        "zhuandantxt" =>$config['zhuandantxt'],
        "zhuandanbegintime" =>date('Y-m-d',$config['zhuandanbegintime']),
        "zhuandanendtime" =>date('Y-m-d',$config['zhuandanendtime']),
        "zhuandantips" =>$config['zhuandantips'],
        "province" =>$config['province'],
        "city" =>$config['city'],
        "district" =>$config['district'],
    );
    $result = array(
        'theme' => array(
            'title'       => $theme ['title'],
            'desc'        => $theme ['desc'],
            'mobile'      => $theme ['mobile'],
            'endtime'     => date('Y-m-d H:i',$theme ['endtime']),
            'status'      => $theme ['status'],
            'jubf'      => $theme ['jubf']
        ),
        'config' => $confignew,
        'system' => $systemnew,
    );

    return $result;
}
static function w_index($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);

    $info['scansum'] = Record::getscannumByThemeId($themeid,$config['showalldata'])+intval($config['fakescan']);
    
    $groupsnum = Record::getFansNumByThemeId($themeid,$config['showalldata']);
    $info['fansnum'] = intval($groupsnum)+intval($config['faketuan']);;

    $info['forward'] = Record::getforwardnumByThemeId($themeid,$config['showalldata']);
    if ($myworker['level'] == '1'){
        //删除重复员工
        Worker::WorkerDeleteChongfu($themeid);

        $info['recordcount'] = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                WHERE  themeid = '{$themeid}' and status > 0  and status!=3" ));
        $info['recordxxcount'] = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
            WHERE r.themeid ='{$themeid}'  and r.status = '3' " ));
        $ordercount = floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                WHERE themeid = '{$themeid}' and paystate = 1 and realfee > 0 " ));
        $info['ordercount'] = sprintf("%.2f", $ordercount);

        $shouxu = 1 - Order::shouxufei();
        $shouxu2 = Order::shouxufei();

        $commcount = floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}'  and status  = 1 " ));
        $info['commcount'] = -sprintf("%.2f", $commcount);

        $info['shuxufei'] = sprintf("%.2f",$ordercount*$shouxu2);

        $info['chongzhi'] = $theme['chongzhi'];

        $info['shijidaozhao'] =sprintf("%.2f",$info['ordercount']*$shouxu+$info['commcount']+$theme['chongzhi']);


        if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $info['recordcount']==0){
            $tongjitiaojian ='';
        }else{
            $tongjitiaojian =' and status > 0 ';
        }
        if (!empty($config['addressoptions'])) {
            $options1=array();
            foreach ($config['addressoptions'] as $index => $item) {
                $tempa = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE themeid ='{$themeid}' and  `address` like '%" . $item . "%' " . $tongjitiaojian ));
                array_push($options1, array('name'=>$item,'value'=>$tempa));
            }
        }

        if (!empty($config['options'])) {
            if (!empty($config['gudingoptions'])) {
                $configoptions = array_merge($config['gudingoptions'],$config['options']);
            }else{
                $configoptions = $config['options'];
            }            
            $options2=array();
            foreach ($configoptions as $index => $item) {
                $tempa = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE themeid ='{$themeid}' and  `option` like '%" . $item . "%' " . $tongjitiaojian ));
                array_push($options2, array('name'=>$item,'value'=>$tempa));
            }
        }

    }else{
        $total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
        $info['totalsum']= $total1 + $config['fakejoin'];

        if ($config['showalldata']==0) {
            $noalldata = " and themeid =" .$themeid;
        }

        $starttime = strtotime( date('Y-m-d 00:00'));  
        $info['today'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                WHERE  status > 0 and addtime > '{$starttime}' " . $noalldata );

        $info['my'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and workerid = '{$_G['member']['uid']}' " . $noalldata );
    }

    if ($config['ishexiao']==1) {
        if (!empty($myworker['hexiaoerm']) ) {//&& ($fans['hexiaoermtime']+1296000) > TIMESTAMP
            $qrimg = $myworker['hexiaoerm'] ;
        }else{
            //若海报未设置，则只返加二维码
            $scene = MODULE_NAME . "-" . $themeid . "-" . $_G['member']['uid'] . "-" . $theme['softkey'] . "-3" ;
            $qrimg = Poster::CreateScene($system,$scene,'pages/myorder/myorder');
            $qrimg = str_replace('http:', 'https:', $qrimg);
            db_update(t_worker, array('hexiaoerm' =>$qrimg), array('uniacid' => $_G['mpid'], 'themeid' => $themeid, 'openid' => $_G['openid']));
        }
        $info['qrimg'] = $qrimg;
    }

    $confignew = array(
        'showshop' => $config['showshop'],
        'isshoprank' => $config['isshoprank'],
        'isrank' => $config['isrank'],
        'isxianxia' => $config['isxianxia'],
        'isshowxianxia' => $config['isshowxianxia'],
        'dapingurl'=>$config['dapingurl'],
        'address'=>$config['address'],
        'shop'=>$config['shops'],
        'options1' => $options1,
        'options2' => $options2,
        'ishexiao' => $config['ishexiao'],
        'shouxu100'=>$shouxu2*100,
    );

    $result = array(
        'level' => $myworker['level'], 
        'info' => $info, 
        'config' => $confignew, 
    );

    return $result;
}

static function w_input_bangding($fans) {        
    global $_P, $_G;
    $recordid = intval($_P['recordid']);
    $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
    if(!($system['ruanjian']!=3 || $config['showshop']==0 || ($system['ruanjian']==3 && $config['showshop']==$myworker['company']))){
        $myworker = "";
    }
        $sql = "SELECT * FROM " . tablename (t_record) . "
                                    WHERE id = :id and (status > 0 or status=-2) ";
        $record = db_find($sql, array(":id"=>$recordid));

        if (!empty($record['openid'])){
            if($record['openid'] == $_G['openid']){
                $result = array(
                    'msg' => '已绑定成功',
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "此定单已绑定微信:".$record['nickname'] );
            }
        }
        if (empty($myworker)) {
            $data = array(
                'openid'   => $_G['openid'],
                'uid'      => $_G['member']['uid'],
                'nickname' => $fans['nickname'],
                'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
                'pid'      => $recordid,
            );

            $r = db_update(t_record,$data,array("id"=>$record['id']));
            if(!empty($r)){
                $result = array(
                    'msg' => '绑定成功',
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "保存失败请重试" );
            }
        }else{
            return array('error' =>1 , 'msg' => "只有非员工的微信才可以扫码绑定" );
        }

}
static function w_input($system,$theme,$config,$myworker) {        
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $recordid = intval($_P['recordid']);

    // if ($config['isxianxia']==0){
    //  return_msg('无权访问');
    // }
    if ($op=='display' || $op=="getinfo") {
        $confignew = array(
            'shopstype' => $config['shopstype'],
            'shops' => $config['shops'],
            'options' => $config['options'],
            'addresstype' => $config['addresstype'],
            'address' => $config['address'],
            'addressoptions' => $config['addressoptions'],                
            'optionsnew' => $config['optionsnew'],
            'nametext' => $config['nametext'],
            'mobiletext' => $config['mobiletext'],
            'datetimetype' => $config['datetimetype'],
            'datetime' => $config['datetime'],
            'shopstype' => $config['shopstype'],
            'iseditorder' => $config['iseditorder'],
            'maxcountall' => $config['maxcountall'],
        );
        if($config['isxianxia']==1 || $myworker['level'] == 1){
            $confignew['isxianxia'] = true;
        }else{
            $confignew['isxianxia'] = false;
        }

        $feelist = array();

        if ($config['joinfee'] != '0.00' && !empty($config['joinfee'])){
            yxlog($system['jiage']);
            if ($system['jiage']==0) {
                $payname = '定金';
            }else{
                $payname = $config['joinname'];
            }
            array_push($feelist, array('name'=>$payname,'fee'=>$config['joinfee']));
        }
        if ($config['joinfee2'] != '0.00' && !empty($config['joinfee2'])){
            array_push($feelist, array('name'=>$config['joinname2'],'fee'=>$config['joinfee2']));
        }
        if ($config['joinfee3'] != '0.00' && !empty($config['joinfee3'])){
            array_push($feelist, array('name'=>$config['joinname3'],'fee'=>$config['joinfee3']));
        }
        if ($config['groupprice'] != '0.00' && !empty($config['groupprice'])){
            array_push($feelist, array('name'=>'拼团价','fee'=>$config['groupprice']));
        }
        if ($config['groupprice2'] != '0.00' && !empty($config['groupprice2'])){
            array_push($feelist, array('name'=>'拼团价②','fee'=>$config['groupprice2']));
        }
        if ($config['primeprice'] != '0.00' && !empty($config['primeprice'])){
            array_push($feelist, array('name'=>'单买价','fee'=>$config['primeprice']));
        }
        foreach ($feelist as $index => $item) {
            $feelist[$index]['fullname']=$item['name'].$item['fee'];
        }

        $result=array();
        $result['op']=$op;
        $result['config']=$confignew;
        $result['feelist'] = $feelist;

        if ($op=="getinfo"){
            $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                    WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
            $result['qrimg']=$record['avatar'];
            $result['username']=$record['username'];
            $result['mobile']=$record['mobile'];
            $result['record']=$record;
        }
        $result['level']=$myworker['level'];
        return $result;
    }elseif ($op == 'save') {
        $username = $_P['username'];
        $mobile = $_P['mobile'];
        $realfee = $_P['realfee'];
        $payname = $_P['payname'];

        if (empty($username) || empty($mobile)) {
            return array('error' =>1 , 'msg' => "客户姓名与电话不可为空" );
        }

        if (empty($realfee) || $realfee == "0.00"){
            if ($config['joinfee'] != "0.00"){
                $realfee=$config['joinfee'];
            }elseif ($config['groupprice'] != "0.00"){
                $realfee=$config['groupprice'];
            }else{
                $realfee=$config['primeprice'];
            }
        }
        if ($payname == "拼团价②" && $config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $realfee==$config['groupprice2']){
            $renshu = 1;
        }else{
            $renshu = 0;
        }
        if ($payname == "单买价" && $config['primeprice'] != '0.00' && !empty($config['primeprice']) && $realfee==$config['primeprice']){
            $paytype = 9;
        }else{
            $paytype = 0;
        }

        $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
        $data = array(
            'uniacid'  => $_G['mpid'],
            'themeid'  => $themeid,
            'openid'   => '',
            'uid'      => '',
            'nickname' => '',
            'avatar'   => '',
            'username' => $username,
            'mobile'   => $mobile,
            'addtime'  => TIMESTAMP,
            'fee'      => $realfee,
            'option' => $_P['option'],
            'address' => $_P['address'],
            'datetime' => $_P['datetime'],
            'code'     => '',
            'uncode'   => $uncode,
            'status'   => 3,
            'fromuid'  => $_G['member']['uid'],
            'fopenid'  => $_G['openid'],
            'workerid'  => $_G['member']['uid'],
            'pid'      => 0,
            'type'     => $paytype,
            'renshu'     => $renshu,
        );

        $addtime = TIMESTAMP-120;
            $sql = "SELECT * FROM " . tablename (t_record) . "
                                        WHERE themeid =:themeid and username = :username
                                                and mobile = :mobile and type = 0 and status=3 and addtime >" . $addtime . " ";
            $row = db_find($sql, array(":themeid"=>$themeid,":username"=>$username,":mobile"=>$mobile));

        if (!empty($row)) {
            return array('error' =>1 , 'msg' =>"客户“".$username."”在2分钟内录入过线下定单，若实际为多个定单请在2分钟以后再次录入" );
        } else {
            Theme::workerreport($themeid,$_G['member']['uid'],array('recordxx' =>1));
            $r = $insertid = db_insert(t_record,$data);
        }
        
        if(!empty($r)){
            $recordid = $insertid;
            $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;

            $qrimg = Poster::CreateScene($system,$scene,'pages/w_input/w_input');
            // echo $qrimg;
            $data = array(
                'nickname' => '未绑定客户微信',
                'avatar'   => $qrimg,
            );
            $r = db_update(t_record,$data,array("id"=>$recordid));
        }
        $result = array(
            'qrimg' => $qrimg,
            'username' => $username,
            'mobile'   => $mobile,
        );
        $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
        $result['record']=$record;
        return $result;
    }
}

static function w_myinfo($system,$theme,$config,$myworker) {   
    global $_P, $_G;
    $themeid = intval($_P['themeid']);

    if ($config['showalldata']==0) {
        $noalldata2 = " and themeid =" .$themeid;
    }

    //更新顶部统计数据
    $paycount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and workerid = '{$_G['member']['uid']}' " . $noalldata2 );
    $unpaidcount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status = 0 and workerid = '{$_G['member']['uid']}' " . $noalldata2 );
    $paycounttoday = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and workerid = '{$_G['member']['uid']}' and addtime>'{$todaytime}' " . $noalldata2 );
    $unpaidcounttoday = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status = 0 and workerid = '{$_G['member']['uid']}' and addtime>'{$todaytime}' " . $noalldata2 );

    $directcount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and fromuid = '{$_G['member']['uid']}' and workerid = '{$_G['member']['uid']}'" . $noalldata2 );
    $directcounttoday = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and fromuid = '{$_G['member']['uid']}' and addtime>'{$todaytime}' and workerid = '{$_G['member']['uid']}'" . $noalldata2 );

    $data = array (
        'paycount' => $paycount,
        'directcount' => $directcount,
        'commcount'=> $commcount,
        'commsum'  => $commsum,
        'commfail' => $commfail,
        'directsum'  => $directsum,
        'paysum' => $paysum,
        'unpaidcount' => $unpaidcount,
        'paycounttoday'=> $paycounttoday,
        'unpaidcounttoday'  => $unpaidcounttoday,
        'directcounttoday'  => $directcounttoday,
    );
    db_update (t_worker, $data, array ('openid' => $_G['openid'],'themeid' => $themeid) );
    $my = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);

    if ($config['showalldata']==0) {
        $noalldata = " and  w.themeid =" .$themeid ." ";
    }

    $starttime = strtotime( date('Y-m-d 00:00'));  
    if ($my['level'] == '2' && $myworker['company']!=0){  
        $my['teampaycount'] = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_record ) . " r
        left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
        WHERE w.company = '{$myworker['company']}' and r.status > 0 " . $noalldata);

        $my['teampaycounttoday'] = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_record ) . " r
        left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
        WHERE w.company = '{$myworker['company']}' and r.status > 0 and r.addtime > '{$starttime}'" . $noalldata );
        $my['teamtips'] ="所在商家";
    }elseif ($my['level'] == '2' && $myworker['team']!=0){  
        $my['teampaycount'] = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_record ) . " r
        left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
        WHERE w.team = '{$myworker['team']}' and r.status > 0 " . $noalldata );
        $my['teampaycounttoday'] = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_record ) . " r
        left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
        WHERE w.team = '{$myworker['team']}' and r.status > 0 and r.addtime > '{$starttime}'" . $noalldata );
        $my['teamtips'] ="所在团队";
    }else{
        $my['teampaycount'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 " . $noalldata2 );
        $my['teampaycounttoday'] =  db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0 and addtime > '{$starttime}'" . $noalldata2 );
        $my['noworker'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0  and status!=3" . $noalldata2 );
        $my['teamtips'] ="所有";
    }
    if ($my['level'] == '1'){
        $my['username'] = $myworker['username'] . "【超级管理员】";
    }elseif ($my['level'] == '2'){
        $my['username'] = $myworker['username'] . "【商家管理员】";
    }elseif ($my['level'] == '3'){
        $my['username'] = $myworker['username'] . "【员工】";
    }

    $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$myworker['company']}'");
    $team=db_find("SELECT * FROM ".tablename(t_team)." WHERE id= '{$myworker['team']}'");
    if (empty($shop['name'])){
        $my['teamname']=$team['name'];
    }else{
        $my['teamname']=$shop['name'] . " - " . $team['name'];
    }
    if (empty($my['teamname'])) {
        $my['teamname'] = $my['username'];
        $my['username'] = "昵称：" . $myworker['nickname'];
    }
    $my['paycounttoday']=sprintf("%+d",$my['paycounttoday']);
    $my['unpaidcounttoday']=sprintf("%+d",$my['unpaidcounttoday']);
    $my['directcounttoday']=sprintf("%+d",$my['directcounttoday']);
    $my['teampaycounttoday']=sprintf("%+d",$my['teampaycounttoday']);


    //个人日报
    if ($config['showalldata']==0) {
        $myreport = db_select("SELECT *, right(riqi,5) as riqi FROM " . tablename ( t_workerreport ) . " WHERE themeid ='{$themeid}' and workerid = '{$_G['member']['uid']}' order by riqi desc" );
    }else{
        $myreport = db_select("SELECT right(riqi,5) as riqi,sum(newfans) as newfans,sum(forward) as forward,sum(scansum) as scansum,sum(recordzx) as recordzx,sum(record) as record,sum(recordxx) as recordxx,sum(fee) as fee,sum(comm) as comm FROM " . tablename ( t_workerreport ) . " WHERE workerid = '{$_G['member']['uid']}' group by riqi order by riqi desc" );
    }


    if ($myworker['level'] != '3' || ($myworker['level'] == '3' && $config['isreport']==1)){
        if ($config['showalldata']==0) {
            $noalldata = " w.themeid =" .$themeid ." and ";
        }

        $myteam = db_select("SELECT right(r.riqi,5) as riqi, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
            left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid
            WHERE " . $noalldata . " w.team = " . $myworker['team'] ." and w.company = " . $myworker['company'] ." group by r.riqi order by riqi desc" );

        $mycompany = db_select("SELECT right(r.riqi,5) as riqi, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
            left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid
            WHERE " . $noalldata . " w.company = " . $myworker['company'] ." group by r.riqi order by riqi desc" );

        $notworker = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0  and status!=3 and workerid = '' and themeid = '{$themeid}' " );

        if ($notworker>0) {
            $workertips = "【{$notworker}个定单无客服】";
        }else{
            $workertips = "";
        }
    }

    $result = array(
        'my' =>$my,
        'myreport' =>$myreport,
        'myteam' =>$myteam,
        'mycompany' =>$mycompany,
        'workertips' =>$workertips,
    );
    return $result;
}


static function w_report($system,$theme,$config,$myworker) {   
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $todaytime = strtotime(date("Y-m-d 00:00:00"));
    $shopname='';

    if ($system['ruanjian']==3) {
        if (!empty($myworker['company'])) {
            $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$myworker['company']}'");
            $shopname=" - " . $shop['name'] ;
        }
    }
    if ($myworker['level'] != '3' || ($myworker['level'] == '3' && $config['isreport']==1)){

        if ($config['showalldata']==0) {
            $noalldata = " and w.themeid =" .$themeid;
        }

        if ($system['ruanjian']==3) {
            $sql = 'SELECT t.id as tid, t.name as teamname FROM ' . tablename ( t_team ) . " t
                    WHERE t.company = :company 
                    ORDER BY t.id  ";
            $team = db_select($sql, array(":company"=>$myworker['company']));
        }else{
            $sql = 'SELECT t.id as tid, t.name as teamname FROM ' . tablename ( t_team ) . " t
                    ORDER BY t.id  ";
            $team = db_select($sql );
        }

        foreach ($team as $index => $item) {
            $myteam = db_select("SELECT right(r.riqi,5) as riqi, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
            left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
            WHERE 1=1 " . $noalldata ." and w.team = " . $item['tid'] ." group by r.riqi order by riqi desc" );
            $team[$index]['list'] = $myteam;
        }

        $mycompany = db_select("SELECT right(r.riqi,5) as riqi, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
            left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
            WHERE 1=1 " . $noalldata ." and w.company = " . $myworker['company'] ." group by r.riqi order by riqi desc" );

        if ($system['ruanjian']==3 && $myworker['level'] == '1') {
            $allcompany = db_select("SELECT right(r.riqi,5) as riqi, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
            left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
            WHERE 1=1 " . $noalldata ." group by r.riqi order by riqi desc" );
        }

        $notworker = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE status > 0  and status!=3 and workerid = '' and themeid = '{$themeid}' " );

        if ($notworker>0) {
            $workertips = $shopname."【{$notworker}个定单无客服】";
        }else{
            $workertips = $shopname;
        }
    }else{
        return array('error' =>1 , 'msg' => "您无权限查阅");
    }

    $result = array(
        'team' =>$team,
        'mycompany' =>$mycompany,
        'allcompany' =>$allcompany,
        'workertips' =>$workertips,

    );
    return $result;
}

static function w_report_ren($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    if ($myworker['level'] != '3') {
        if ($myworker['level'] == '1') {
            $sql = 'SELECT w.uid,w.username,w.company,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
                    left join " . tablename ( t_team ) . " as t on w.team = t.id
                    left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                    WHERE w.mobile<>'' and w.themeid = :themeid
                    ORDER BY company,team,uid  ";
            $wlist = db_select($sql, array(":themeid"=>$themeid));   
        }else{
            $sql = 'SELECT w.uid,w.username,w.company,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
                    left join " . tablename ( t_team ) . " as t on w.team = t.id
                    left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                    WHERE w.mobile<>'' and w.themeid = :themeid AND w.company = :company
                    ORDER BY company,team,uid  ";
            $wlist = db_select($sql, array(":themeid"=>$themeid,":company"=>$myworker['company']));  
        }

        $uid = $_P['uid'];
        if (empty($uid)) {
           $uid = $_G['member']['uid'];
        }

        foreach ($wlist as $index => $item) {
            if (!empty($item['companyname'])) {
                $item['companyname'] .= "-";
            }
            if (!empty($item['teamname'])) {
                $item['teamname'] .= "-";
            }
            $wlist[$index]['name']=$item['companyname'] . $item['teamname'] . $item['username'];
            if ($item['uid']==$uid) {
                $wlistindex = $index;
            }
        }

        $info = Worker::getThemeWorkerByUid($_P['uid'],$themeid);
        if ($config['showalldata']==0) {
            $report = db_select("SELECT *,right(riqi,5) as riqi FROM " . tablename ( t_workerreport ) . " WHERE themeid ='{$themeid}' and workerid = '{$uid}' order by riqi desc" );
        }else{
            $report = db_select("SELECT right(r.riqi,5) as riqi,sum(newfans) as newfans,sum(forward) as forward,sum(scansum) as scansum,sum(recordzx) as recordzx,sum(record) as record,sum(recordxx) as recordxx,sum(fee) as fee,sum(comm) as comm FROM " . tablename ( t_workerreport ) . " WHERE workerid = '{$uid}' group by riqi order by riqi desc" );
        }
    }else{
        return array('error' =>1 , 'msg' => "您无权限查阅");
    }

    $result = array(
        'report' =>$report,
        'wlist' =>$wlist,
        'wlistindex' => $wlistindex,
    );
    return $result;
}
static function w_ranktuan($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $op = $_P['op'];

    if ($myworker['level']==3) {
        $tiaojian = " and workerid = " . $_G['member']['uid'];
    }else{
        $tiaojian ="";
    }

    if ($op=='ranktuan') {        
        if ($myworker['level'] == 1 || $config['isrank']==1 || ($myworker['level']==2 && $config['isshoprank']==1)){
            if ($myworker['level']==3 || ($myworker['level']==2 && $config['isshoprank']==0)) {
                $tiaojian = " and workerid = " . $_G['member']['uid'];
            }else{
                $tiaojian ="";
            }
            $ranktuan = db_select("SELECT * FROM ".tablename(t_record)."
                            WHERE  themeid =" . $themeid . $tiaojian . " and status > 0 and type = 0 ORDER BY tuannum desc,addtime desc limit 100");
            foreach ($ranktuan as $index => $item) {
                $ranktuan[$index]['idnew']= $item['id']+10000;
                $ranktuan[$index]['username'] = mb_substr($item['username'],0,4,'utf-8');
            }
        }else{
            return array('error' =>1 , 'msg' => "您无权限查阅");
        }
    }
    if ($op=='rankfans') {        
        if ($myworker['level'] == 1 || $config['isrank']==1 || ($myworker['level']==2 && $config['isshoprank']==1)){
            if ($myworker['level']==3 || ($myworker['level']==2 && $config['isshoprank']==0)) {
                $tiaojian = " and workerid = " . $_G['member']['uid'];
            }else{
                $tiaojian ="";
            }
            $paixu = $_P['paixu'];
            //sortlist:['成交数排名','推荐数排名','转发量排名','浏览量排名'],
            if ($paixu=='3') {
                $sortinfo = '粉丝浏览量排名';
                $sorttxt = ' order by scansum desc,tuijian desc,responsum desc,id desc';
            }elseif ($paixu=='2') {
                $sortinfo = '粉丝转发量排名';
                $sorttxt = ' order by forward desc,tuijian desc,responsum desc,id desc';
            }elseif ($paixu=='1') {
                $sortinfo = '粉丝推荐排名';
                $sorttxt = ' order by responsum desc,tuijian desc,id desc';
            }else {
                $sortinfo = '粉丝成交排名';
                $sorttxt = ' order by tuijian desc,responsum desc,id desc';
                db_update(t_fans, array('tuijian' => 0 ));
                $record = db_select("SELECT fromuid FROM ".tablename(t_record)."
                                    WHERE themeid =" . $themeid ." and status > 0 and fromuid > 0 order by id desc");
                foreach ($record as $index => $item) {
                    db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijian + 1 WHERE themeid = '{$themeid}' and uid ={$item['fromuid']}");
                }
            }

            $sql = "SELECT * FROM ".tablename(t_fans)."
                WHERE scansum>0 and themeid =" . $themeid ." ". $tiaojian . $sorttxt ." limit 100";
            $rankfans = db_select($sql);


            foreach ($rankfans as $index => $item) {
                $rankfans[$index]['idnew']= $item['id']+10000;
                if (empty($item['username'])) {
                    $rankfans[$index]['name'] = mb_substr($item['nickname'],0,4,'utf-8');
                }else{
                    $rankfans[$index]['name'] = mb_substr($item['username'],0,4,'utf-8');
                }
            }
        }else{
            return array('error' =>1 , 'msg' => "您无权限查阅");
        }
    }
    $result = array(
        'ranktuan' =>$ranktuan,
        'rankfans' =>$rankfans,
        'wlistindex' => $wlistindex,
    );
    return $result;
}
static function w_example($system,$theme,$config,$myworker) {   
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $id = intval($_P['id']);
    if ($id>0){
        $sql = "SELECT r.addtime,r.status,r.isrefund,r.nickname,r.avatar,o.uniontid,o.transaction_id,o.realfee,r.workerid FROM " . tablename ( t_record ) . " as r
            left join " . tablename ( t_order ) . " as o on r.id = o.masterid
            WHERE r.themeid ='{$themeid}' and o.paystate=1 and o.realfee>0 and r.id ='{$id}'";
            //echo $sql;
        $order  = db_find ( $sql );

        if (empty($order)){
            return array('error' =>1 , 'msg' => "错误:未付款/已退款/线下定单均无凭证" );
        }elseif ($order['status'] == 0){
            return array('error' =>1 , 'msg' => "此定单未付款" );
        }elseif ($order['status'] < 0){
            if ($item['isrefund']==2){
                return array('error' =>1 , 'msg' => "此定单已自动退款" );
            }else{
                return array('error' =>1 , 'msg' => "此定单已手工退款" );
            }
        }
    }else{
        //return_msg("自动生成定单");
        $kaishishu = rand(1,700);
        $xuni1 = db_find ("SELECT nickname,username,avatar FROM " . tablename('2019xuni_fans') . " where id =". $kaishishu );

        $kaishishu = rand(1,700);
        $xuni2 = db_find ("SELECT nickname as username,avatar FROM " . tablename('2019xuni_fans') . " where   id =". $kaishishu );

        //2个价格
        if ($system['jiage']==0) {
            if ($config['joinfee'] != "0.00"){
                $realfee=$config['joinfee'];
            }
        }elseif ($system['jiage']==1) {
            if ($config['joinfee'] != "0.00" && $config['joinfee2'] != "0.00"){
                if (rand(0, 10)<6){
                    $realfee=$config['joinfee'];
                }else{
                    $realfee=$config['joinfee2'];
                }
            }else{
                if ($config['joinfee'] != "0.00"){
                    $realfee=$config['joinfee'];
                }else{
                    $realfee=$config['joinfee2'];
                }
            }
        }elseif ($system['jiage']==2) {
            if ($config['joinfee'] != "0.00" && $config['joinfee2'] != "0.00" && $config['joinfee3'] != "0.00"){
                if (rand(0, 10)<4){
                    $realfee=$config['joinfee'];
                }elseif (rand(0, 10)<6){
                    $realfee=$config['joinfee2'];
                }else{
                    $realfee=$config['joinfee3'];
                }
            }
        }
        //2个拼团价
        if (empty($realfee) || $realfee == "0.00"){
            if ($system['ruanjian']==4) {
                if ($config['groupprice2'] != "0.00" && $config['groupprice'] != "0.00" && $config['primeprice'] != "0.00"){
                    if (rand(0, 10)<4){
                        $realfee=$config['groupprice2'];
                    }elseif (rand(0, 10)<6){
                        $realfee=$config['groupprice'];
                    }else{
                        $realfee=$config['primeprice'];
                    }
                }else{
                    if ($config['groupprice'] != "0.00"){
                        $realfee=$config['groupprice'];
                    }else{
                        $realfee=$config['primeprice'];
                    }
                }
            }
        }
        if (empty($realfee) || $realfee == "0.00"){
            if ($config['groupprice'] != "0.00" && $config['primeprice'] != "0.00"){
                if (rand(0, 10)<7){
                    $realfee=$config['groupprice'];
                }else{
                    $realfee=$config['primeprice'];
                }
            }else{
                if ($config['groupprice'] != "0.00"){
                    $realfee=$config['groupprice'];
                }else{
                    $realfee=$config['primeprice'];
                }
            }
        }

        $transaction_id = "42000002" . rand(51,96) . date("YmdHis"). rand(10000,99999)  . rand(10000,99999);
        $uniontid = getMillisecond();
        $uniontid = date("Y").mb_substr($uniontid,4,24,'utf-8');
        $order = array(
            'addtime' => TIMESTAMP, 
            'nickname' =>$xuni1['nickname'], 
            'avatar' =>$xuni2['avatar'], 
            'realfee' =>$realfee, 
            'transaction_id' => $transaction_id, 
            'uniontid' => $uniontid, 
        );

    }

    $sharedata = array(
        'themeid'=>$themeid,
        'fopenid'=>$_G['openid'],
        'fromuid'=>$_G['member']['uid'],
        'workerid'=>$myworker['uid'],
        'flag'=>1,
    );
    

    // if ($system['gongzhong'] =='1'){
    //     $domaintxt = $system['domainhead1'];
    // }else{
    //     $domaintxt = DOMAIN0;
    // }
    // $workerurl = "https://".$domaintxt."/".createMobileUrl('index',$sharedata);
    
    // $workerurl = Poster::GetExampleUrl($system,$workerurl,MODULE_NAME ."员工:".$myworker['username']);

    $xiaoshu = round(($order['realfee']-floor($order['realfee']))*100);
    $order['zhengshu'] =floor($order['realfee']);
    $order['xiaoshu'] = $xiaoshu<10?"0".$xiaoshu:$xiaoshu;
    $order['addtime'] = date("Y-m-d H:i:s", $order['addtime']);
    $order['transaction_id'] = mb_substr($order['transaction_id'],0,16,'utf-8') . "******" . mb_substr($order['transaction_id'],22,6,'utf-8');
    $order['uniontid'] = mb_substr($order['uniontid'],0,16,'utf-8') . "******" . mb_substr($order['uniontid'],22,6,'utf-8');

    return $order;
}

    static function w_orderedit($system,$theme,$config,$myworker) {        
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        $do = 'order';
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        $id = intval($_P['id']);

        if ($myworker['level']!=1 && $config['iseditorder']==0) {
           return array('error' =>1 , 'msg' =>"无权修改订单" );
        }
        if ($op=='display') {
            if ($system['softstyle']==5) {
                $tuanzhang = $config['jmbiemingwenzi'];
                $danmai = $config['jmbiemingwenzi2'];
            }else{
                $tuanzhang = '团长';
                $danmai = '单买'; 
            }

            if($id == 0) {
                return array('error' =>1 , 'msg' =>"定单信息不存在" );
            }
            $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                    WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $id));
            if ($record['type']==0 ) {
                $record['pid'] = $record['id'];
            }

            $uid = $record['uid'];
            if($uid != 0) {
                $fansinfo = db_find('SELECT * FROM ' . tablename(t_fans) . ' 
                    WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $themeid,':uid' => $uid));
            }

            if(empty($record)) {
                // return_tips('定单信息不存在', $url, 'success');
                return;
            }

            $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
                    left join " . tablename ( t_team ) . " as t on w.team = t.id
                    left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                    WHERE w.themeid = :themeid
                    ORDER BY company,team,uid  ";
            $wlist = db_select($sql, array(":themeid"=>$themeid));

            // if ($myworker['level']==1) {
                $wlistnew = array();
                foreach ($wlist as $index => $row) {
                    if ($record['workerid']==$row['uid']) {
                        $wlist_index=$index;
                    }
                    $wlistnew[$index]['name'] = "";
                    if ($system['ruanjian']==3){
                        $wlistnew[$index]['name'] = $wlistnew[$index]['name'] . $row['companyname'] . "-";
                    }
                    $wlistnew[$index]['name'] = $wlistnew[$index]['name']. $row['teamname'] . "-" .$row['username'] . "-" .$row['mobile'];
                    $wlistnew[$index]['value'] = $row['uid'];
                }
            // }
            if ($myworker['level'] == '1'){ 
                $tiaojian = "";
            }elseif ($myworker['level'] == '2'){
                $tiaojian = " and  w.company = " . $myworker['company'];
            }else{
                $tiaojian = " and  workerid = " . $myworker['uid'];
            }

            $tuanlist = db_select("SELECT r.id,r.username,r.mobile FROM " . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . ' as w on r.workerid = w.uid and r.themeid = w.themeid 
                WHERE r.id = ' . $record['pid'] .' order by r.mobile asc');

            foreach ($tuanlist as $index => $item) {
                $tuanlist[$index]['renshu'] = Record::getAttendDetailNumByPId($item['id'])+1;
            }

            $tuanlistnew = array();
            foreach ($tuanlist as $index => $row) {
                if ($record['pid']==$row['id']) {
                    $tuanlist_index=$index;
                }
                $tuanid = $row['id']+10000;
                $tuanlistnew[$index]['name'] = $row['username']."【".$row['mobile']."】已有" . $row['renshu'] ."人 团号". $tuanid ;
                $tuanlistnew[$index]['value'] = $row['id'];
            }

            //多选处理
            if ($config['shopstype'] == 4 && $config['shops'] && $config['options']) {
                $options = $config['options'];
                foreach ($options as $index => $row) {
                    if(strpos("||".$record['option'], "|".$row . "|")){
                        $config['optionsnew'][$index]['checked']=true;
                        $config['optionsnew'][$index]['name']=$row;
                    }else{
                        $config['optionsnew'][$index]['checked']=false;
                        $config['optionsnew'][$index]['name']=$row;
                    }
                }
            }
            $confignew = array(
                'shopstype' => $config['shopstype'],
                'shops' => $config['shops'],
                'options' => $config['options'],
                'optionsnew' => $config['optionsnew'],
                'addresstype' => $config['addresstype'],
                'address' => $config['address'],
                'addressoptions' => $config['addressoptions'], 
                'nametext' => $config['nametext'],
                'mobiletext' => $config['mobiletext'],
                'datetimetype' => $config['datetimetype'],
                'datetime' => $config['datetime'],
                'shopstype' => $config['shopstype'],
                'iseditorder' => $config['iseditorder'],
                'maxcountall' => $config['maxcountall'],
            );
            if($config['iseditorder']==1 || $myworker['level'] == 1){
                $confignew['isedit'] = true;
            }else{
                $confignew['isedit'] = false;
            }
            $systemnew = array(
                'ruanjian' => $system['ruanjian'],
            );

            if ($record['type']==0){
                $record['shenfen'] = $tuanzhang;
            }elseif ($record['type']==1){
                $record['shenfen'] = '团员';
            }elseif ($record['type']==9){
                $record['shenfen'] = $danmai;
            }
            $result=array();
            $result['op']=$op;
            $result['system']=$systemnew;
            $result['level']=$myworker['level'];
            $result['config']=$confignew;
            $result['record']=$record;
            $result['tuanlist']=$tuanlistnew;
            $result['tuanlist_index']=$tuanlist_index;
            $result['wlist']=$wlistnew;
            $result['wlist_index'] = $wlist_index;
            $result['record']['chongzhi'] = $fansinfo['chongzhi'];
            $result['record']['fansbeizhu'] = $fansinfo['beizhu'];

            return $result;
        }elseif ($op=='save'){

            $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                    WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $id));
            $uid = $record['uid'];     
            $beizhu = ''; 
            if ($record['type']==0 ) {
                $record['pid'] = $record['id'];
            }
                $opuser = $myworker['username'];
                if ($config['iseditorder']==1 || $myworker['level'] == '1') {
                    $data = array(
                            'username' => trim($_P['username']),
                            'mobile' => trim($_P['mobile']),
                            'option' => $_P['option'],
                            'address' => $_P['address'],
                            'datetime' => $_P['datetime'],
                        ); 

                    if ($data['username']!=$record['username']) {
                        $beizhu .= date('m-d H:i') . ' ' . $config['nametext'] . '：'.$record['username'].' 改为 ' . $data['username'] . ' 操作:' . $opuser . '<br>';
                    }
                    if ($data['mobile']!=$record['mobile']) {
                        $beizhu .= date('m-d H:i') . ' ' . $config['mobiletext'] . '：'.$record['mobile'].' 改为 ' . $data['mobile'] . ' 操作:' . $opuser . '<br>';
                    }
                    if ($data['option']!=$record['option']) {
                        $beizhu .= date('m-d H:i') . ' ' . $config['shops'] . '：'.$record['option'].' 改为 ' . $data['option'] . ' 操作:' . $opuser . '<br>';
                    }
                    if ($data['address']!=$record['address']) {
                        $beizhu .= date('m-d H:i') . ' ' . $config['address'] . '：'.$record['address'].' 改为 ' . $data['address'] . ' 操作:' . $opuser . '<br>';
                    }
                    if ($data['datetime']!=$record['datetime']) {
                        $beizhu .= date('m-d H:i') . ' ' . $config['datetime'] . '：'.$record['datetime'].' 改为 ' . $data['datetime'] . ' 操作:' . $opuser . '<br>';
                    }
                }else{
                    $data = array();
                }

                if ($myworker['level'] == '1'){

                    $workerid = $_P['workerid'];
                    $iszhixiao="";
                    if ($workerid != $record['workerid'] ){
                        $data['workerid'] = $workerid;
                        if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
                            $data['workerid_old']  = $workerid;
                        }
                        $tempa = Worker::getThemeWorkerNameByUid($record['workerid'],$themeid,$system['ruanjian']);
                        $tempb = Worker::getThemeWorkerNameByUid($workerid,$themeid,$system['ruanjian']);
                        $beizhu .= date('m-d H:i') . ' 所属员工：'. $tempa .' 改为 ' . $tempb . ' 操作:' . $opuser . '<br>';
                        //更新日报表
                        if ($record['status']==3) {
                            if ($workerid ==$record['fromuid']) {
                                $zhixiao ="recordxx = recordxx +1,";
                            }
                            db_query("UPDATE ".tablename(t_workerreport)." SET recordxx = recordxx + 1," . $zhixiao . "fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                            if ($record['workerid']==$record['fromuid']) {
                                $iszhixiao ="recordxx = recordxx -1,";
                            }
                            db_query("UPDATE ".tablename(t_workerreport)." SET recordxx = recordxx -1," . $iszhixiao . " fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                        }else{
                            if ($workerid ==$record['fromuid']) {
                                $zhixiao ="recordxx = recordxx +1,";
                            }
                            db_query("UPDATE ".tablename(t_workerreport)." SET record = record +1," . $zhixiao . "fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                            if ($record['workerid']==$record['fromuid']) {
                                $iszhixiao ="recordxx = recordxx -1,";
                            }
                            db_query("UPDATE ".tablename(t_workerreport)." SET record = record -1," . $iszhixiao . " fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                        }
                    }
                }

                if ($config['iseditorder']==1 || $myworker['level'] == '1') {
                    $tuanid = $_P['tuanid'];
                    if ($tuanid != $record['pid'] && $config['maxcountall']>1){
                        $data['pid'] = $tuanid;
                        $data['type'] = 1;
                        $tempa = $record['pid']+10000;
                        $tempb = $tuanid+10000;
                        if ($record['type']==0){
                            $shenfen = $tuanzhang;
                        }elseif ($record['type']==1){
                            $shenfen = '团员';
                        }elseif ($record['type']==9){
                            $shenfen = $danmai;
                        }
                        $beizhu .= date('m-d H:i') . ' 所属团：'. $tempa . $shenfen .' 改为 ' . $tempb . '团员 操作:' . $opuser . '<br>';
                    }
                }
                if (!empty($beizhu)) {
                    $data['beizhu'] = $record['beizhu'] . $beizhu;
                    writelogcz($system,$themeid,'修改定单',"订单：" . $record['id'] . " 姓名:" . $record['username'] ." 电话:" . $record['mobile'] . '<br>' . $beizhu) ;
                }
                db_update(t_record, $data, array('id' => $_P['id']));

                if ($config['iseditorder']==1 || $myworker['level'] == '1') {
                    //更新团状态
                    if ($tuanid != $record['pid'] && $config['maxcountall']>1){
                        $count = Record::getAttendDetailNumByPId($record['pid']);
                        db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $record['pid']) );
                        if ($record['renshu']==1) {
                            $neednum = intval($config['maxcountall2'])-1;
                        }else{
                            $neednum = intval($config['maxcountall'])-1;
                        }
                        if($count >= $neednum){
                            Record::setIsfinish($record['pid']);
                        }else{
                            Record::setNofinish($record['pid']);
                        }
                        if ($record['type']==0){
                            $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                                        WHERE  ord.themeid ='{$themeid}' 
                                        and (status > 0 or status = -2) and type = 1 and ord.pid='{$record['pid']}' 
                                        ORDER BY ord.addtime asc ";
                            $list = db_find ( $sql,$params);
                            if (!empty($list)){
                                $beizhu = $list['beizhu'];
                                $beizhu .= date('m-d H:i') . ' 因团长【'.$record['username'].'】转走，成为新团长 操作:' . $opuser . '<br>';
                                $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array('id' => $list['id']));
                                $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $record['pid']));
                                $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                                
                            }
                        }

                        $count = Record::getAttendDetailNumByPId($tuanid);
                        db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $tuanid) );
                        if ($record['renshu']==1) {
                            $neednum = intval($config['maxcountall2'])-1;
                        }else{
                            $neednum = intval($config['maxcountall'])-1;
                        }
                        if($count >= $neednum){
                            Record::setIsfinish($tuanid);
                        }else{
                            Record::setNofinish($tuanid);
                        }
                    }
                }

                if ($config['iseditorder']==1 || $myworker['level'] == '1') {
                    $data = array(
                            'username' => trim($_P['username']),
                            'mobile' => trim($_P['mobile']),
                        );
                    db_update(t_record, $data, array('id' => $_P['id']));
                    db_update(t_order, $data, array('masterid' => $_P['id']));         
                }
                $data = array();
                $data ['chongzhi'] = floatval($_P['chongzhi']);
                $data ['beizhu'] = $_P['beizhu'];
                db_update(t_fans, $data, array('uid' => $uid));       

            $result = array('error' => 0 );
            return $result;
        }
            
        if($op == 'refund' && $myworker['level'] == '1') {
            $refundno = getMillisecond();
            //return_msg('暂时关闭,如需退款请联系易宣工作人员');
            if (!empty($theme['jiezhang'])){
                return array('error' =>1 , 'msg' => "此活动已结算,无法退款" );
            }
            
            $trade = Order::getPayOrderByRIdZhifude($id);
            if (empty($trade)){
                return array('error' =>1 , 'msg' =>"此定单未支付或已退" );
            }
            $refundfee = Order::getRealByThemeIdRefund($themeid);
            if ($refundfee>=$theme['refundfee']){
                return array('error' =>1 , 'msg' =>'可退'.$theme['refundfee'].'单,授权已用完,请联系工作人员授权!' );
            }


            $totalpayfee = Order::getRealByThemeIdnew($themeid) + $theme['chongzhi'] - $trade['realfee'];
            if ($totalpayfee<1){
                return array('error' =>1 , 'msg' =>"您的余额不足,无法退款,需先充值再退款" );
            }

            $ret = Util::applyrefund($trade,$refundno,$system);
            if ($ret['code']==0){
                Record::deleterecord($system,$themeid,$id);
                $state = db_update(t_order, array('paystate' => -1,'refundtime'=>TIMESTAMP), array('id' => $trade['id']));
                $tuanzhang = Record::getPayedGroupById($id,$themeid);

                $item = Record::getById($id);
                $beizhu = $item['beizhu']. date('m-d H:i') . ' 全额退款 操作:' . $opuser . '<br>';
                $state = db_update(t_record, array('status' => -1,'isrefund'=>1,'refundtime'=>TIMESTAMP,'beizhu'=>$beizhu), array('id' => $id));
                $state = db_update(t_record, array('isfinish' => 0), array('pid' => $id));

                $count = Record::getAttendDetailNumByPId($id);
                db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $id) );
                
                if (empty($tuanzhang)){
                    return array('error' =>1 , 'msg' =>"退款成功！" );
                }else{
                    $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                                WHERE  ord.themeid ='{$themeid}' 
                                and (status > 0 or status = -2) and type = 1 and ord.pid='{$id}' 
                                ORDER BY ord.addtime asc ";
                    $list = db_find ( $sql,$params);
                    if (empty($list)){
                        return_msg('退款成功！', $url, 'success');
                    }else{
                        $state = db_update(t_record, array('type' => 0), array('id' => $list['id']));
                        $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $id));
                        $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                        $url = createWebUrl($do,array('op2' => 'scan','id' => $list['id'],'themeid'=>$themeid));
                        return array('error' =>1 , 'msg' =>'退款成功！'.$list['username'].'成为新团长' );
                    }
                }
            }else{
                return array('error' =>1 , 'msg' =>$ret['message'] );
            }

        }
        if($op == 'newtuan'){
            $item = Record::getById($id);
            // $p = array(":openid"=>$item['openid'],":themeid"=>$themeid);
            // $item2 = db_find ( "SELECT * FROM " . tablename ( t_record ) . " 
            //          WHERE openid = :openid and themeid =:themeid and type = 0 and status != 0",$p);
            // if(!empty($item2)){
            //  return_tips('当前粉丝已经是团长了');
            // }
            if(empty($item['status'])){
                return array('error' =>1 , 'msg' => "该定单未付款");
            }
            $data = array(
                    'uniacid'  => $_G['mpid'],
                    'themeid'  => $themeid,
                    'openid'   => $item['openid'],
                    'uid'      => $item['uid'],
                    'nickname' => $item['nickname'],
                    'avatar'   => $item['avatar'],
                    'username' => $item['username'],
                    'mobile'   => $item['mobile'],
                    'addtime'  => TIMESTAMP,
                    'fee'      => $config['joinfee'],
                    'address'  => $item['address'],
                    'datetime' => $item['datetime'],
                    'option'   => $item['option'],
                    'status'   => -2,
                    'fromuid'  => $item['uid'],
                    'fopenid'  => $item['openid'],
                    'workerid'  => $item['workerid '],
                    'pid'      => 0,
                    'type'     => 0,
                    'uncode'   => $themeid.'-'.TIMESTAMP.rand(1000,1000000)
            );
            $r = $insertid = db_insert(t_record,$data);
            $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$item['mobile'],"themeid"=>$themeid));
            return array('error' =>1 , 'msg' => "开新团成功！");
        }
        if($op == 'uptuanzhang') {    
            $item = Record::getById($id);
            $beizhu = $item['beizhu']. date('m-d H:i') . ' 单买升级为拼团 操作:' . $opuser . '<br>';
            $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array('id' => $id));
            $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));
            return array('error' =>1 , 'msg' => "单买升级为拼团成功！");
        }
        if($op == 'xunifinish') {
            $item = Record::getById($id);
            $beizhu = $item['beizhu']. date('m-d H:i') . ' 设置虚拟成团 操作:' . $opuser . '<br>';
            $state = db_update(t_record, array('xunifinish' =>1,'beizhu'=>$beizhu), array('pid' => $id));
            $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));

            return array('error' =>1 , 'msg' => "虚拟成团设置成功");
        }
        if($op == 'unxunifinish') {
            $item = Record::getById($id);
            $beizhu = $item['beizhu']. date('m-d H:i') . ' 取消虚拟成团 操作:' . $opuser . '<br>';
            $state = db_update(t_record, array('xunifinish' =>0,'beizhu'=>$beizhu), array('pid' => $id));
            $url = $_G['siteroot']. createMobileUrl('w_order',array("op2"=>"search","searchtxt"=>$_P['mobile'],"themeid"=>$themeid));

            return array('error' =>1 , 'msg' => "取消虚拟成团设置成功");
        }

    }
    static function w_fans($system,$theme,$config,$myworker) {        
        global $_P, $_G;
        $op = !empty($_P['op']) ? $_P['op'] : 'all';
        $themeid = intval($_P['themeid']);
        if ($myworker['level'] == '1'){ 
            if ($op=='all'){
                $tiaojian = "";
            }elseif ($op=='company'){
                $tiaojian = " and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and  f.workerid = " . $myworker['uid'];
            }
        }elseif ($myworker['level'] == '2'){
            if ($op=='all' || $op=='company'){
                $op='all';
                $tiaojian = " and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and  f.workerid = " . $myworker['uid'];
            }
        }else{
            $op='my';
            $tiaojian = " and  f.workerid = " . $myworker['uid'];
        }


        $pageNumber = max ( 1, intval ( $_P['page'] ) );
        $pageSize = 10;

        if ($pageNumber==1) {
            $gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . " as f
                left join " . tablename ( t_worker ) . " as w on f.workerid = w.uid and f.themeid = w.themeid
                WHERE f.themeid ='{$themeid}' and (f.mobile!='' or f.nickname!='' or f.avatar!='')  " . $tiaojian . "" ));
             
            $gsum16 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . " as f
                left join " . tablename ( t_worker ) . " as w on f.workerid = w.uid and f.themeid = w.themeid
                WHERE f.themeid ='{$themeid}' " . $tiaojian . " and f.username='' and f.mobile!='' " ));

            $todaytime =  strtotime(date('Y-m-d 00:00:00'));
            $gsum17 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . " as f
                left join " . tablename ( t_worker ) . " as w on f.workerid = w.uid and f.themeid = w.themeid
                WHERE f.themeid ='{$themeid}' and f.addtime > '{$todaytime}' and (f.mobile!='' or f.nickname!='' or f.avatar!='')  " . $tiaojian . "" ));

        }

        $op2 = $_P['op2'] ;
        $show = $_P['show'];

        $itemheight = 3.3;

    if(!isset($_P['scan'])){
        $type = -1;
    }else{
        $type = intval($_P['scan']);
    }
    if ($type==5) {
        $sorttxt = ' order by f.scansum desc,f.id desc';
    }elseif ($type==6) {
        $sorttxt = ' order by f.forward desc,f.id desc';
    }elseif ($type==11) {
        $sorttxt = ' order by f.responsum desc,f.id desc';
        // db_update(t_fans, array('responsum' => 0 ));
        if ($pageNumber==1) {
            db_query("UPDATE ".tablename(t_fans)." SET responsum = responsumxuni WHERE  themeid = '{$themeid}'");
            $record = db_select("SELECT fromuid FROM ".tablename(t_scan)."
                                WHERE  themeid =" . $themeid );
            foreach ($record as $index => $item) {
                db_query("UPDATE ".tablename(t_fans)." SET responsum = responsum + 1 WHERE  themeid = '{$themeid}' and uid ={$item['fromuid']}");
            }
        }
    }elseif ($type==4) {
        $sorttxt = ' order by f.tuijian desc,f.id desc';
        if ($pageNumber==1) {
            db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijianxuni WHERE  themeid = '{$themeid}'");
            $record = db_select("SELECT fromuid FROM ".tablename(t_record)."
                                WHERE  themeid =" . $themeid ." and status > 0 and fromuid > 0 order by id desc");
            foreach ($record as $index => $item) {
                db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijian + 1 WHERE  themeid = '{$themeid}' and uid ={$item['fromuid']}");
            }
        }
    }else{
        $sorttxt = ' order by f.id desc';
    }

    $condition = 'where f.themeid = ' . $themeid ;
    if (intval($_P['keyword'])>0) {
        if (strlen($_P['keyword'])==11 || strstr($_P['keyword'],'.')) {
            $condition .= " AND (f.mobile LIKE '%{$_P['keyword']}%' or f.ip LIKE '%{$_P['keyword']}%') ";
        }else{
            $workerurl = $_G['siteroot'] . createWebUrl('scan', array('op' => 'display','themeid'=>$themeid,'keyword'=>$_P['keyword']));
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$workerurl';"; 
            echo "</script>";  
            exit;
        }
    }elseif(!empty($_P['keyword'])) {
        $condition .= " AND ( f.ipaddress LIKE '%{$_P['keyword']}%' or f.nickname LIKE '%{$_P['keyword']}%' or f.username LIKE '%{$_P['keyword']}%') ";
    }

    if (empty($_P['createtime']['start'])){
        $starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
        $starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
    }else{
        $starttime =  strtotime($_P['createtime']['start']);
    }
    $endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
    $condition.= " and f.addtime > '{$starttime}' and f.addtime <= '{$endtime}' ";
    
    
    if ($type==7) {
        $condition.= " and f.status < 1 ";
    }

    if ($type==8) {
        $condition.= " and f.status > 1 ";
    }
    if ($type==9) {
        $condition.= " and f.username='' and f.mobile!='' ";
    }
    if ($type==17) {
        $todaytime =  strtotime(date('Y-m-d 00:00:00'));
        $condition.= " and f.addtime > '{$todaytime}' ";
    }

    if ($type!=10) {
        $condition.= " and (f.mobile!='' or f.nickname!='' or f.avatar!='')  ";
    }else{
        $condition.= " and (f.mobile='' and f.nickname='' and f.avatar='')  ";
    }

    // echo $condition .$tiaojian . $sorttxt;

        $total = db_fetchcolumn ("SELECT count(f.id)  FROM " . tablename ( t_fans ) . " as f
                left join " . tablename ( t_worker ) . " as w on f.workerid = w.uid and f.themeid = w.themeid " . $condition .$tiaojian );
 

        $sql  = "SELECT f.*,w.username as workername FROM " . tablename ( t_fans ) . " as f
                left join " . tablename ( t_worker ) . " as w on f.workerid = w.uid and f.themeid = w.themeid "  . $condition .$tiaojian . $sorttxt ." LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $orders  = db_select ( $sql);

        if (!empty($orders)){
            foreach ($orders as $index => $item) {
                if($config['isicon'] > 0){
                    $lightsum=0;
                    if($config['iconnum2'] <= 0){
                        $lightsum = Share::getNumByThemeIdAndOpenidAndStatus($themeid,$item['openid'],1);
                    }else{
                        $lightsum = Scan::getNumByThemeIdAndOpenidAndStatus($themeid,$item['openid'],1);;
                        $lightsum = intval($lightsum/$config['iconnum2']);
                    }
                    if($lightsum >= $config['iconnum']){
                        $lightsum = $config['iconnum'];
                    }
                }

                $scan = db_find ( "SELECT * FROM " . tablename ( t_scan ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['uid']));
                $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$scan['fromuid']));


                if(!empty($item['workerid'])){
                    $fans = db_find ("SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
                        left join " . tablename ( t_team ) . " as t on w.team = t.id
                        left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                        WHERE w.uid = :uid and w.themeid =:themeid
                        ",array(":themeid"=>$themeid,":uid"=>$item['workerid']));
                    $orders[$index]['workername'] = $fans['username'];
                    $orders[$index]['teamname'] = $fans['teamname'];
                    $orders[$index]['companyname'] = $fans['companyname'];
                    
                }
                
                $orders[$index]['workernameall'] = "电话：" . $item['mobile'];

                $orders[$index]['sid'] = $total - ($pageNumber - 1) * $pageSize-$index;

                $orders[$index]['addtime'] = date("Y-m-d H:i:s", $item['addtime']);
                $orders[$index]['nickname'] = $item['nickname'];

                $orders[$index]['avatar'] = tomedia($item['avatar']);

                $moreinfo =  array( );
                $txttemp = "上级:" . $scan['fromuid'] ."-".  mb_substr($fans['nickname'],0,12,'utf-8') . "";
                array_push($moreinfo,$txttemp);
                $txttemp = "浏览:{$orders[$index]['scansum']}次";
                array_push($moreinfo,$txttemp);
                $txttemp = "转发:{$orders[$index]['forward']}次";
                array_push($moreinfo,$txttemp);
                if($config['isicon'] > 0){
                    $txttemp = "星星:" .$lightsum ."颗";
                    array_push($moreinfo,$txttemp);
                }
                if ($orders[$index]['chongzhi']!="0.00" && !empty($orders[$index]['chongzhi'])){
                    $txttemp = "会员卡:{$orders[$index]['chongzhi']}";
                    array_push($moreinfo,$txttemp);
                }
                if ($myworker['level']==3) {
                    $txttemp = "销售:";
                    if ($system['ruanjian']==3){
                        $txttemp .=mb_substr($orders[$index]['companyname'],0,8,'utf-8') . "-";
                    }
                    $txttemp .= $orders[$index]['teamname'] ."-" . $orders[$index]['workername']. "";
                    array_push($moreinfo,$txttemp);
                }

                $orders[$index]['moreinfo']  = $moreinfo;
            }
        }
        $info=  array();
        $info['gsum16'] = $gsum16;
        $info['gsum17'] = $gsum17;
        $info['gsumall'] = $gsumall;
        $result=  array();
        $result['info'] = $info;
        $result['list'] = $orders;
        $result['page'] = $pageNumber;
        $result['totalPage'] =  ceil($total / $pageSize)-1;
        $result['totalSize'] =  $total-$pageSize;

        if ($pageNumber*$pageSize>=$total) {
            $result['hasNext'] = false ;
        }else{
            $result['hasNext'] = true  ;
        }
        return $result;
    }

    static function w_order($system,$theme,$config,$myworker) {        
        global $_P, $_G;
        $op = !empty($_P['op']) ? $_P['op'] : 'all';
        $themeid = intval($_P['themeid']);
        if ($myworker['level'] == '1'){ 
            if ($op=='all'){
                $tiaojian = "";
            }elseif ($op=='company'){
                $tiaojian = " and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and  r.workerid = " . $myworker['uid'];
            }
        }elseif ($myworker['level'] == '2'){
            if ($op=='all' || $op=='company'){
                $op='all';
                $tiaojian = " and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and  r.workerid = " . $myworker['uid'];
            }
        }else{
            $op='my';
            $tiaojian = " and  r.workerid = " . $myworker['uid'];
        }


        $pageNumber = max ( 1, intval ( $_P['page'] ) );
        $pageSize = 10;

        if ($pageNumber==1) {
            $gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . "" ));


            $gsum0 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 0 and r.status > 0 " ));
            $gsum1 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 1 and r.status > 0 " ));
            $gsum9 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 9 and r.status > 0 " ));
            $gsum10 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.isfinish = 0 and r.xunifinish = 0" ));
            $gsum11 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and (r.isfinish = 1 or r.xunifinish = 1 )"));
            $gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.status!=3 " ));
            $gsum13 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 0 " ));
            $gsum14 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = '-1' " ));
            $gsum15 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = '3' " ));
        }

        $id = intval($_P['id']);
        if ($id > 0){
            $op='all';
            $tiaojian = " and  r.id = " . $id;
        }


        $op2 = $_P['op2'] ;
        $show = $_P['show'];
        if ($system['softstyle']==5) {
            $tuanzhang = $config['jmbiemingwenzi'];
            $danmai = $config['jmbiemingwenzi2'];
        }else{
            $tuanzhang = '团长';
            $danmai = '单买'; 
        }
        if ($show=='kezi'){
            $do = 'kezi';
        }else{
            $do = 'order';
        }

        $itemheight = 3.3;
        if (!empty($config['address'])){
            $itemheight = $itemheight+0.3;
        }
        if (!empty($config['shops'])){
            $itemheight = $itemheight+0.3;
        }
        if (!empty($config['datetime'])){
            $itemheight = $itemheight+0.3;

        }
        $scan = intval($_P['scan']);

        switch ($scan) {
            case '0':
                $sql="WHERE r.themeid ='{$themeid}' ". $tiaojian;
                break;
            case '30':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 0 and r.status > 0";
                break;
            case '1':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 1 and r.status > 0";
                break;
            case '9':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 9 and r.status > 0";
                break;
            case '10':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.isfinish = 0 and r.xunifinish = 0";
                break;
            case '11':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and (r.isfinish = 1 or r.xunifinish = 1)";
                break;
            case '12':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.status !=3";
                break;
            case '13':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 0 ";
                break;
            case '14':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = '-1' ";
                break;
            case '15':
                $sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 3 ";
                break;
            default:
                $sql="WHERE r.themeid ='{$themeid}' ". $tiaojian;
                break;
        }

            //获得按扭文字
            if ($config['groupprice2']>0) {
                $gruoptips = $config['formtextcenter2'];
                $gruoptips = str_replace("#fee",'',$gruoptips);
                $gruoptips = str_replace("#dan",'',$gruoptips);
                $gruoptips = str_replace("#tuan",'',$gruoptips);
                $gruoptips = str_replace("#br",'',$gruoptips);
                $gruoptips = str_replace("￥",'',$gruoptips);
                $gruoptips2 = $gruoptips ;

                $gruoptips = $config['formtextcenter'];
                $gruoptips = str_replace("#fee",'',$gruoptips);
                $gruoptips = str_replace("#dan",'',$gruoptips);
                $gruoptips = str_replace("#tuan",'',$gruoptips);
                $gruoptips = str_replace("#br",'',$gruoptips);
                $gruoptips = str_replace("￥",'',$gruoptips);

                if (empty($config['formtextcenter'])) {
                    $gruoptips = $config['maxcountall']."人团";
                }
                if (empty($config['formtextcenter2'])) {
                    $gruoptips2 = $config['maxcountall2']."人团";
                }
            }
                
        if ($op2=="search") {
            $keyword = $_P['searchtxt'];
            if (!empty($keyword)) {
                if (intval($keyword)>10000 && intval($keyword)<30000) {
                    $tempa = intval($keyword)-10000;
                    $sql.= " and (r.pid = '". $tempa . "' or r.id = '". $tempa. "') ";
                } else {
                    $sql .= " and (r.nickname like '%{$keyword}%' or r.username like '%{$keyword}%' or r.mobile like '%{$keyword}%' or r.option like '%{$keyword}%' or r.address like '%{$keyword}%' or r.datetime like '%{$keyword}%')";
                }
            }
        }
            
              //       $sql =  "SELECT COUNT(ord.id) FROM " . tablename ( t_record ) . " as ord WHERE  ord.pid = '{$row['id']}'";
                // $dtotal = db_fetchcolumn ($sql);
        $condition = $sql;

        $total = db_fetchcolumn ("SELECT count(r.id)  FROM " . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid " . $condition ."
                order by r.addtime desc ");

        $sql  = "SELECT r.*,w.username as workername FROM " . tablename ( t_record ) . " as r
                left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid " . $condition ."
                order by r.addtime desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $orders  = db_select ( $sql);

        if (!empty($orders)){
            foreach ($orders as $index => $item) {
                if (empty($item['uid'])) {
                    $item['uid']=-2341234;
                }
                $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['uid']));
                $orders[$index]['scansum']=$fans['scansum'];
                $orders[$index]['forward']=$fans['forward'];
                $orders[$index]['chongzhi']=$fans['chongzhi'];
                $orders[$index]['isshow']  = false;

                if(!empty($item['fromuid'])){
                    $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['fromuid']));
                    if (!empty($fans['username'])){
                        $orders[$index]['tjr']=$fans['username'];
                    }elseif (!empty($fans['nickname'])){
                        $orders[$index]['tjr']=$fans['nickname'];
                    }else{
                        $orders[$index]['tjr']=$item['fromuid'];
                    }           
                }else{
                    $orders[$index]['tjr']="无";
                }

                if ($system['fanpai']==1){
                    $pm = array(":themeid"=>$themeid,":openid"=>$item['openid']);
                    $yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
                    WHERE themeid = :themeid and openid = :openid",$pm);
                    $list[$index]['fanpaichoujiang'] = $yichou;

                    $jihui = $config['fanpailimit']- $yichou;
                    $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['uid']));
                    $list[$index]['fanpaijihui'] =  ($jihui>$fans['jihui']) ? $fans['jihui'] : $jihui ;
                }

                if(!empty($item['workerid'])){
                    $fans = db_find ("SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
                        left join " . tablename ( t_team ) . " as t on w.team = t.id
                        left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                        WHERE w.uid = :uid and w.themeid =:themeid
                        ",array(":themeid"=>$themeid,":uid"=>$item['workerid']));
                    $orders[$index]['workername'] = $fans['username'];
                    $orders[$index]['teamname'] = $fans['teamname'];
                    $orders[$index]['companyname'] = $fans['companyname'];

                    if ($myworker['level'] ==3 ){ 
                        $orders[$index]['workernameall'] = "电话：" . $item['mobile'];
                    }else{
                        if ($system['ruanjian']==3){
                            $txttemp = mb_substr($orders[$index]['companyname'],0,5,'utf-8') . "-";
                        }else{
                            $txttemp = mb_substr($orders[$index]['teamname'],0,5,'utf-8') . "-";
                        }
                        $txttemp .= $orders[$index]['workername'];
                        $orders[$index]['workernameall'] = "销售：" . $txttemp;
                    }
                }
                
                if ($system['ruanjian']==0 && $system['softstyle']==5 && !empty($item['address'])) {
                    $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= '" . $item['address']."'");
                    $xianname = $itemdz['areaName'];
                    if (!empty($itemdz)){
                        $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $itemdz['parentId']);
                        $shiname = $itemdz['areaName'];
                    }
                    if (!empty($itemdz)){
                    $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $itemdz['parentId']);
                    $shengname = $itemdz['areaName'];
                    }
                    $orders[$index]['address'] = $shengname . $shiname .$xianname;
                }



                $orders[$index]['sid'] = $total - ($pageNumber - 1) * $pageSize-$index;

                $orders[$index]['addtime'] = date("Y-m-d H:i:s", $item['addtime']);
                $orders[$index]['nickname'] = $item['nickname'];

                if ($item['uid']==-2341234) { 
                    $orders[$index]['avatar'] = $_G['URL']['FCWORK_CSS'] . 'images/avatar1.jpg';
                }else{
                    $orders[$index]['avatar'] = tomedia($item['avatar']);
                }
                if ($item['status'] ==-2){
                    $txttemp = "虚拟订单";
                }elseif ($item['status'] < 0){
                    if ($item['isrefund']==2) {
                        $txttemp = "自动退款";
                    } else {
                        $txttemp = "手工退款";
                    }
                }elseif ($item['status'] == 1){
                    $txttemp = "已支付"; //<span>￥<i>" . $item['fee'] . "</i></span>
                }elseif ($item['status'] == 0){
                    $txttemp = "未支付";
                }elseif ($item['status'] == 3){
                    $txttemp = "线下定单";
                }
                $orders[$index]['statustxt'] = $txttemp;

                // $orders[$index]['exampleurl'] = "/".createMobileUrl('w_example',array("themeid"=>$themeid,"id"=>$item['id']));
                // $orders[$index]['orderediturl'] = "/".createMobileUrl('w_orderedit',array("themeid"=>$themeid,"id"=>$item['id'],"uid"=>$item['uid']));
                // $orders[$index]['inputurl'] = "/".createMobileUrl('w_input',array("themeid"=>$themeid,"op"=>"bangding","recordid"=>$item['id']));

                $txttemp = "<a href='" . $orders[$index]['orderediturl'] . "' class='changeBtn'>修改订单</a>";

                if ($item['status'] == 3 && empty($item['openid'])){
                    $txttemp .= "    <a href='" . $orders[$index]['inputurl'] . "' class='checkBtn'>绑定微信</a>";
                }elseif ($item['status'] == 1){
                    $txttemp .= "   <a href='" . $orders[$index]['exampleurl'] . "' class='checkBtn'>交易凭证</a>";
                }
                // if ($config['maxcount']>0 && $item['tuannum']>1) {
                //     $txttemp .= "   <a href='" ."/".createMobileUrl('w_group',array("themeid"=>$themeid,"op"=>'all',"pid"=>$item['pid'])) . "' class='checkBtn checkBtn3'>团成员</a>";
                // }
                $orders[$index]['urltxt']  = $txttemp;

                $moreinfo =  array( );
                if ($myworker['level']!=3) {
                    $txttemp = "电话：{$item['mobile']}";
                    array_push($moreinfo,$txttemp);
                }
                if (!empty($config['address'])){
                    $txttemp = "{$config['address']}：{$item['address']}";
                    array_push($moreinfo,$txttemp);
                }
                if (!empty($config['shops'])){
                    $txttemp = "{$config['shops']}：{$item['option']}";
                    array_push($moreinfo,$txttemp);
                }
                if (!empty($config['datetime'])){
                    $txttemp = "{$config['datetime']}：{$item['datetime']}";
                    array_push($moreinfo,$txttemp);
                }
                $txttemp = "浏览:{$orders[$index]['scansum']}次";
                array_push($moreinfo,$txttemp);
                $txttemp = "转发:{$orders[$index]['forward']}次";
                array_push($moreinfo,$txttemp);
                $txttemp = $orders[$index]['statustxt'] . ":￥{$orders[$index]['fee']}元";
                array_push($moreinfo,$txttemp);
                $txttemp = "推荐人:" .  mb_substr($orders[$index]['tjr'],0,12,'utf-8') . "";
                array_push($moreinfo,$txttemp);

                if ($orders[$index]['chongzhi']!="0.00" && !empty($orders[$index]['chongzhi'])){
                    $txttemp = "会员卡:{$orders[$index]['chongzhi']}";
                    array_push($moreinfo,$txttemp);
                }
                if ($myworker['level']==3) {
                    $txttemp = "销售:";
                    if ($system['ruanjian']==3){
                        $txttemp .=mb_substr($orders[$index]['companyname'],0,8,'utf-8') . "-";
                    }
                    $txttemp .= $orders[$index]['teamname'] ."-" . $orders[$index]['workername']. "";
                    array_push($moreinfo,$txttemp);
                }

                if ($config['maxcount']>0){
                    $item['pid'] = $item['pid'] +10000;
                    $txttemp = "团号:" . $item['pid'] . "";
                    array_push($moreinfo,$txttemp);
                    $txttemp = "团人数:" . $item['tuannum'] . "人";
                    array_push($moreinfo,$txttemp);

                    if ($item['isfinish']==1){
                        $txttemp = "团状态:拼团成功";
                    }elseif ($item['xunifinish']==1){
                        $txttemp = "团状态:虚拟成团";
                    }else{
                        $txttemp = "团状态:拼团中";
                    }
                    array_push($moreinfo,$txttemp);

                    if ($item['type']==0) {
                        $txttemp = "团身份:团长";
                        $orders[$index]['shenfen']  = "团长";
                    }elseif ($item['type']==9) {
                        $txttemp = "团身份:单买";
                        $orders[$index]['shenfen']  = "单买";
                    }else {
                        $txttemp = "团身份:团员";
                        $orders[$index]['shenfen']  = "团员";
                    }
                    array_push($moreinfo,$txttemp);
                    if ($config['groupprice2']>0 && $item['type']!=9){
                        if ($item['renshu']==0){
                            $txttemp = "团套餐:" . $gruoptips . "";
                        }else{
                            $txttemp = "团套餐:" . $gruoptips2 . "";
                        }
                        array_push($moreinfo,$txttemp);
                    }
                }
                $orders[$index]['moreinfo']  = $moreinfo;
            }
        }
        $info=  array();
        $info['gsum12'] = $gsum12;
        $info['gsum13'] = $gsum13;
        $info['gsum15'] = $gsum15;
        $info['gsum0'] = $gsum0;
        $info['gsum1'] = $gsum1;
        $info['gsum9'] = $gsum9;
        $info['maxcount'] = $config['maxcount'];
        $result=  array();
        $result['info'] = $info;
        $result['list'] = $orders;
        $result['page'] = $pageNumber;
        $result['totalPage'] =  ceil($total / $pageSize)-1;
        $result['totalSize'] =  $total-$pageSize;

        if ($pageNumber*$pageSize>=$total) {
            $result['hasNext'] = false ;
        }else{
            $result['hasNext'] = true  ;
        }
        return $result;
    }
    static function w_group($system,$theme,$config,$myworker) {
        global $_P, $_G;
        $op = !empty($_P['op']) ? $_P['op'] : 'all';
        $themeid = intval($_P['themeid']);
        $do = 'group';
        $pid = intval($_P['id']);

        if ($myworker['level'] == '1'){ 
            if ($op=='all'){
                $tiaojian = "";
            }elseif ($op=='company'){
                $tiaojian = " and r.status > 0 and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and r.status > 0 and  r.workerid = " . $myworker['uid'];
            }
        }elseif ($myworker['level'] == '2'){
            if ($op=='all' || $op=='company'){
                $op='all';
                $tiaojian = " and r.status > 0 and  w.company = " . $myworker['company'];
            }else{
                $op='my';
                $tiaojian = " and r.status > 0 and  r.workerid = " . $myworker['uid'];
            }
        }else{
            $op='my';
            $tiaojian = " and r.status > 0 and  r.workerid = " . $myworker['uid'];
        }

        $pageNumber = max ( 1, intval ( $_P['page'] ) );
        $pageSize = 10;
        if ($_P['show']=='get') {
            $pageNumber = $pageNumber + 1;
        }


        $groupsnum  = db_fetchcolumn ( "SELECT count(*) FROM " . tablename ( t_record ) . " as r
                    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                    WHERE r.themeid = :themeid " . $tiaojian . " and r.type = 0 and r.status > 0 ", array(":themeid"=>$themeid) );
        $total =$groupsnum;

        $groupsnumall  = db_fetchcolumn ( "SELECT count(*) FROM " . tablename ( t_record ) . " as r
                    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                    WHERE r.themeid = :themeid " . $tiaojian . " and r.status > 0 ", array(":themeid"=>$themeid) );
        $groupsnumtuanyuan  = db_fetchcolumn ( "SELECT count(*) FROM " . tablename ( t_record ) . " as r
                    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                    WHERE r.themeid = :themeid " . $tiaojian . " and r.type = 1 and r.status > 0 ", array(":themeid"=>$themeid) );
        
        if ($pid > 0){
            $op='all';
            $tiaojian = " and  r.pid = " . $pid;
        }

        $sql = "SELECT  r.*,w.username as workername FROM " . tablename ( t_record ) . " as r
                    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                    WHERE r.themeid = " . $themeid  . $tiaojian . " and r.type = 0 and r.status > 0 
                    order by addtime desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $groups  = db_select ( $sql);//LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize );


        foreach ($groups as $index => $item) {
            $groups[$index]['id']=$item['id']+10000;
            if (empty($item['uid'])) {
                $groups[$index]['avatar'] = $_G['URL']['FCWORK_CSS'] . 'images/avatar1.jpg';
            }else{
                $groups[$index]['avatar'] = tomedia($item['avatar']);
            }
            if ($item['tuannum']>1) {
                $groups[$index]['shenfen']="团长";
            }else{
                $groups[$index]['shenfen']="";
            }

            if ($pid ==0 ){
                $temptxt = "and r.status > 0";
            }else{
                $temptxt = "";
            }
            $tuanlist = db_select ( "SELECT r.*,w.username as workername,w.uid as workerid FROM " . tablename ( t_record ) . " as r
                    left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
                    WHERE r.themeid = :themeid and r.status > 0 and r.pid ='" .$item['id']. "' and r.type = 1 ".$temptxt , array(":themeid"=>$themeid) );
            // $groups[$index]['tuannum']=count($tuanlist);
            if (!empty($tuanlist)){
            // if($_G['companyname'] =='飞驰软件'){
                $txttemp="";
                foreach ($tuanlist as $key => $row) {
                    if (empty($item['uid'])) {
                        $tuanlist[$key]['avatar'] = $_G['URL']['FCWORK_CSS'] . 'images/avatar1.jpg';
                    }else{
                        $tuanlist[$key]['avatar'] = tomedia($row['avatar']);
                    }

                    $txttemp .= "           <dt>\n";
                    $txttemp .= "               <div class=\"useImg\"><img src=\"" . $tuanlist[$index]['avatar'] . "\"></div>\n";
                    $txttemp .= "               <div class=\"peopleTxt\">\n";
                    $txttemp .= "                   <h2>" . $row['username'] . "</h2>\n";
                    $txttemp .= "                   <p>昵称：".$row['nickname']."</p>\n";
                    $txttemp .= "               </div>\n";
                    $txttemp .= "               <a href=\"tel:".$row['mobile']."\" class=\"telBtn\"></a>\n";
                    $txttemp .= "           </dt>\n";
                }

                $groups[$index]['tuanlist'] = $tuanlist;
                $groups[$index]['tuanyuan'] = $txttemp;
            // }else{
            //     $tuanyuan = "";
            //     foreach ($tuanlist as $key => $row) {
            //         $xuhao=$key+1;          
            //         $tuanyuan = $tuanyuan . "<dl class='ui-flex'>";
            //         $tuanyuan = $tuanyuan ."    <dt><img class='warp_img' src='".tomedia($row['avatar'])."''></dt>";
            //         $tuanyuan = $tuanyuan ."    <dd>";
            //         $tuanyuan = $tuanyuan ."        <p>" . $xuhao . ". " . date("Y-m-d H:i:s", $row['addtime'])."</p>";
            //         $tuanyuan = $tuanyuan ."        <p>昵称：".mb_substr($row['nickname'],0,8,'utf-8')."</p>";
            //         $tuanyuan = $tuanyuan ."        <p>姓名：".$row['username']."</p>";
            //         $tuanyuan = $tuanyuan ."        <p>电话：".$row['mobile']."</p>";
            //         if(!empty($row['fromuid'])){
            //             $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['fromuid']));
            //             if (!empty($fans['username'])){
            //                 $tuanyuan = $tuanyuan ."        <p>推荐人：".$fans['username']."</p>";
            //             }elseif (!empty($fans['nickname'])){
            //                 $tuanyuan = $tuanyuan ."        <p>推荐人：".$fans['nickname']."</p>";
            //             }else{
            //                 $tuanyuan = $tuanyuan ."        <p>推荐人：".$row['fromuid']."</p>";
            //             }
                        
            //         }else{
            //             $tuanyuan = $tuanyuan ."        <p>推荐人：无</p>";
            //         }
            //         if ($op!='my'){
            //             $tuanyuan = $tuanyuan ."        <p >客服：".$row['workername']."</p>";
            //         }elseif ($row['workerid']!=$myworker['uid']){
            //             $tuanyuan = $tuanyuan ."        <p  style='color: #ff0000'>客服：".$row['workername']."</p>";
            //         }
            //         if ($pid>0) {
            //             if ($row['status'] < 0){
            //                 $tuanyuan = $tuanyuan ."        <p >状态：".$item['isrefund']==2?'自动退款':'手工退款'."</p>";
            //             }elseif ($row['status'] == 1){
            //                 $tuanyuan = $tuanyuan ."        <p >状态：已支付</p>";
            //             }elseif ($row['status'] == 0){
            //                 $tuanyuan = $tuanyuan ."        <p >未支付</p>";
            //             }
            //         }
            //         $tuanyuan = $tuanyuan ."    </dd>";
            //         $tuanyuan = $tuanyuan ."</dl>";
            //     }
            //     $groups[$index]['tuanyuan'] = $tuanyuan;
            // }
            }else{
                $groups[$index]['tuanlist'] = [];
                $groups[$index]['tuanyuan'] = '';
            }
        }

                            
        $result=  array();
        $result['page'] = $pageNumber;
        $result['info']['groupsnumall'] = $groupsnumall;
        $result['info']['groupsnum'] = $groupsnum;
        $result['info']['groupsnumtuanyuan'] = $groupsnumtuanyuan;
        $result['list'] = $groups;
        $result['totalPage'] =  ceil($total / $pageSize)-1;
        $result['totalSize'] =  $total-$pageSize;

        if ($pageNumber*$pageSize>=$total) {
            $result['hasNext'] = false ;
        }else{
            $result['hasNext'] = true  ;
        }
        return $result;
    }

    static function w_rank($system,$theme,$config,$myworker) {
        global $_P, $_G;
        $op = $_P['op'];
        $themeid = intval($_P['themeid']);
        if ($myworker['level'] == '1') {
            $company = empty($_P['company'])?$myworker['company']:$_P['company'];
            $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$company}'");
            $shopname=$shop['name'];
        }
        if (!($myworker['level'] !=3 || $config['isrank']==1 )) {
            return array('error' =>1 , 'msg' => "暂时无权查看，如需查阅请联系店内管理员");
        }
        if (!empty($myworker['company'])) {
            $company = " and w.company = " . $myworker['company'];
        }else{
            $company = "";
        }

        $paixu = $_P['paixu'];
        $show = $_P['show'];
        if ($show =='tuiguang') {
            if ($paixu == 'zf') {
                $paixutxt = "order by forward desc,record desc";
            } elseif ($paixu == 'll') {
                $paixutxt = "order by scansum desc,record desc";
            }else{
                $paixu='';
                $paixutxt = "order by newfans desc,record desc";
            }
        }else{
            if ($paixu == 'fee') {
                $paixutxt = "order by fee desc,record desc";
            } elseif ($paixu == 'xx') {
                $paixutxt = "order by recordxx desc,record desc";
            } else {
                $paixu='';
                $paixutxt = "order by record desc,recordxx desc";
            }
        }


        if ($op == 'search') {
            $starttime = strtotime($_P['starttime']);
            $endtime = empty($_P['endtime']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['endtime'])+59 ;
            //商家排行
            if ($config['showalldata']==0) {
                $noalldata = " and r.themeid =" .$themeid;
            }
            if ($config['isshoprank']==1 || $myworker['level']==1){
                if ($system['ruanjian']==3 && $config['showshop']==0 ) {
                    $companylist = db_select("SELECT s.name as name,sum(case when r.status!=3 THEN 1 else 0 END) as record,sum(case when r.status=3 THEN 1 else 0 END) as recordxx,sum(case when r.status!=3 THEN r.fee else 0 END) as fee FROM " . tablename ( t_record ) . " r
                    left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
                    left join " . tablename ( t_shangjia ) . " s on w.company = s.id
                    WHERE 1=1 " . $noalldata . " and r.status > 0 and r.addtime > '{$starttime}' and r.addtime <= '{$endtime}' group by w.company " . $paixutxt . ",w.company" );
                }
            }
            //自家团队排行

            $teamlist = db_select("SELECT t.name as name,sum(case when r.status!=3 THEN 1 else 0 END) as record,sum(case when r.status=3 THEN 1 else 0 END) as recordxx,sum(case when r.status!=3 THEN r.fee else 0 END) as fee FROM " . tablename ( t_record ) . " r

            left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
            left join " . tablename ( t_team ) . " t on w.team = t.id
            WHERE 1=1 " . $noalldata . " and r.status > 0 and r.addtime > '{$starttime}' and r.addtime <= '{$endtime}' " . $company. "  group by w.team " . $paixutxt . ",w.team" );

            //个人团队排行
            $workerlist = db_select("SELECT w.username as name,sum(case when r.status!=3 THEN 1 else 0 END) as record,sum(case when r.status=3 THEN 1 else 0 END) as recordxx,sum(case when r.status!=3 THEN r.fee else 0 END) as fee FROM " . tablename ( t_record ) . " r

            left join " . tablename ( t_worker ) . " w on w.uid = r.workerid and w.themeid = r.themeid 
            WHERE 1=1 " . $noalldata . " and r.status > 0 and r.addtime > '{$starttime}' and r.addtime <= '{$endtime}' " . $company. "  group by w.uid " . $paixutxt . ",w.team" );


            //总数

            $zongshu = db_find("SELECT sum(case when r.status!=3 THEN 1 else 0 END) as record,sum(case when r.status=3 THEN 1 else 0 END) as recordxx,sum(case when r.status!=3 THEN r.fee else 0 END) as fee FROM " . tablename ( t_record ) . " r
            WHERE 1=1 " . $noalldata . " and r.status > 0 and r.addtime > '{$starttime}' and r.addtime <= '{$endtime}' " );
            
            $starttime = date('Y-m-d H:i',$starttime);
            $endtime   = date('Y-m-d H:i',$endtime);
        }else{
            $starttime = date('Y-m-d 00:00');
            $endtime   = date('Y-m-d 23:59');

            if ($config['showalldata']==0) {
                $noalldata = " and w.themeid =" .$themeid;
            }

            //商家排行
            if ($config['isshoprank']==1 || $myworker['level']==1){
                if ($system['ruanjian']==3 && $config['showshop']==0) {

                    $sql1 = "SELECT w.company,s.name as name, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
                        left join " . tablename ( t_shangjia ) . " s on w.company = s.id
                        left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
                        WHERE 1=1 " . $noalldata ;
                    $sql2 = " group by w.company " . $paixutxt;

                    $companylist = db_select($sql1.$sql2);
                    $companytoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);
                }else{
                    $companylist=null;
                    $companytoday=null;
                }
            }

            $sql1 = "SELECT t.name , w.team, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
                left join " . tablename ( t_team ) . " t on w.team = t.id
                left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
                WHERE 1=1 " . $noalldata . " " . $company ;
            $sql2 = " group by w.team " . $paixutxt . ",w.team";
            // echo $sql1.$sql2;
            $teamlist = db_select($sql1.$sql2);
            $teamtoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);

            $sql1 = "SELECT w.username as name ,w.uid, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
                left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
                WHERE 1=1 " .$noalldata. " " . $company ;
            $sql2 = " group by w.uid " . $paixutxt. ",w.uid";

            $workerlist = db_select($sql1.$sql2);
            $workertoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);

        }

        $result = array(
            'zongshu' =>$zongshu,
            'companylist' =>$companylist, 
            'companytoday' =>$companytoday,
            'teamlist' =>$teamlist, 
            'teamtoday' =>$teamtoday,
            'workerlist' =>$workerlist, 
            'workertoday' =>$workertoday,
        );
        return $result;

    }

    static function getById($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_worker) . " where id = :id";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }

    static function getTotalByShopid($shopid){
        if(empty($shopid)){
            return false;
        }
        $p = array(":shopid"=>$shopid);
        $sql =  "SELECT COUNT(*) FROM" . tablename ( t_worker ) . " WHERE shopid = :shopid";
        $total = db_fetchcolumn ($sql,$p);
        return intval($total);
    }

    static function addTeam($company,$themeid,$groupid,$name){
        global $_G;
        $data = array (
            'groupid' => $groupid,
            'company' => $company,
            'name' => $name,
            'state' => 1,
        );

        if (empty($name)){
            db_delete(t_team, array('groupid' => $groupid,'company'=>$company));
        }else{
            $team = db_find ( "SELECT * FROM " . tablename ( t_team ) . " 
                WHERE groupid=" . $groupid . " and company=" . $company);

            if (! empty ( $team )) {
                db_update ( t_team, $data, array('groupid' => $groupid,'company'=>$company));
            } else {
                // $data ['uniacid'] = $_G['mpid'];
                db_insert ( t_team, $data );
            }
        }
        return true;
    }


    static function getByUId($uid) {
        if (empty($uid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename("mc_members") . " where uid = :uid";
        $row = db_find($sql, array(":uid"=>$uid));
        return $row;
    }

    static function getShoperByShopId($shopid) {
        if (empty($shopid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_worker) . " where identity = 1 and status = 1 and shopid = :shopid limit 1";
        $row = db_find($sql, array(":shopid"=>$shopid));
        return $row;
    }

    static function getListByThemeId($themeid){
        global $_G, $_P;
        if(empty($themeid)){
            return false;
        }
        $params = array();
        $params[':themeid'] = $themeid;
        $fans = db_select("SELECT * FROM ".tablename(t_worker)." WHERE status = 1 and commfee >= 1 and themeid = :themeid",$params);
        return $fans;
    }


    static function getByOpenid($openid,$uniacid){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':uniacid'] = $uniacid;
        $params[':openid'] = $openid;
        $fans = db_find("SELECT * FROM ".tablename(t_worker)." WHERE uniacid= :uniacid and openid = :openid",$params);
        return $fans;
    }

    static function getByMobile($mobile,$uniacid){
        global $_G, $_P;
        if(empty($mobile)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':uniacid'] = $uniacid;
        $params[':mobile'] = $mobile;
        $fans = db_find("SELECT * FROM ".tablename(t_worker)." 
                        WHERE uniacid= :uniacid and mobile = :mobile order by id desc limit 1",$params);
        return $fans;
    }

    static function getThemeWorkerByOpenid($openid,$themeid,$status = 1){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':openid'] = $openid;
        $params[':themeid'] = $themeid;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                        themeid = :themeid and openid = :openid and mobile <>'' and mobile is not null",$params);
        return $row;
    }

    static function getThemeWorkerByOpenidzhuce($openid,$themeid,$status = 1){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':openid'] = $openid;
        $params[':themeid'] = $themeid;
        // $params[':status'] = $status;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                        themeid = :themeid and openid = :openid ",$params);
        return $row;
    }

    static function getThemeWorkerByOpenidAlltheme($openid,$status = 1){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':openid'] = $openid;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE openid = :openid and mobile <>'' and mobile is not null limit 1",$params);
        return $row;
    }
        
    static function gethoutaistats(){
        global $_G, $_P;
        $row = db_find("SELECT * FROM ".tablename("users_permission")." WHERE type = '" . MODULE_NAME ."'");
        if (!empty($row['uid'])) {
            $users = db_find("SELECT * FROM ".tablename("users")." WHERE uid= " . $row['uid'] );
            if ($users['endtime']<TIMESTAMP) {
                $result='后台操作权限已到期';
            }
        // }else{
        //     $result='未找到后台注册信息';
        }
        return $result;
    }    
        
    static function getThemeWorkerByOpenidNew($openid,$themeid){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':openid'] = $openid;
        $params[':themeid'] = $themeid;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                        themeid = :themeid and openid = :openid and mobile <>'' and mobile is not null",$params);
        return $row;
    }
    

    static function getThemeWorkerByUid($uid,$themeid,$status = 1){
        global $_G, $_P;
        if(empty($uid)){
            $uid = $_G['uid'];
        }
        $params = array();
        $params[':uid'] = $uid;
        $params[':themeid'] = $themeid;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                        themeid = :themeid and uid = :uid  and mobile <>'' and mobile is not null",$params);
        return $row;
    }

    static function getThemeWorkerNameByUid($uid,$themeid,$ruanjian = 0){
        global $_G, $_P;
        if(empty($uid)){
            $uid = $_G['uid'];
        }
        $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
            left join " . tablename ( t_team ) . " as t on w.team = t.id
            left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
            WHERE w.themeid = :themeid AND w.uid = :uid";
        $wlist = db_find($sql, array(":themeid"=>$themeid,':uid' => $uid));
        
        if ($ruanjian==3){
            $result = $wlist['companyname'] . '-';
        }else{
            $result ='';
        }
        
        $result .= $wlist['teamname'] . '-' .$wlist['username'];
        return $result;
    }

    static function CopyThemeWorkerByUid($uid,$themeid,$status = 1){
        global $_G, $_P;
        if(empty($uid)){
            $uid = $_G['member']['uid'];
        }

        $theyworker = Worker::getThemeWorkerByUid($uid,$themeid,1);
        if (!empty($theyworker)){
            return $theyworker;
        }

        $params = array();
        $params[':uid'] = $uid;
        $params[':status'] = $status;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE status=:status and uid = :uid",$params);

        $data = array();
        if (!empty($row)){
            $data ['uniacid'] = $_G['mpid'];
            $data ['type'] = $row['type'];
            $data ['themeid'] = $themeid;
            $data ['status'] = 1;
            $data ['uid'] = $row['uid'];
            $data ['openid'] = $row['openid'];
            $data ['addtime'] = TIMESTAMP;
            $data ['username'] = $row['username'];
            $data ['mobile'] = $row['mobile'];
            $data ['team'] = $row['team'];
            $data ['company'] = $row['company'];
            $data ['qrcode'] = $row['qrcode'];
            $data ['nickname'] = $row['nickname'];
            $data ['avatar'] = $row['avatar'];
            $data ['level'] = $row['level'];
            $data ['qruserid'] = $row['qruserid'];

            $params = array();
            $params[':uid'] = $uid;
            $params[':themeid'] = $themeid;
            $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                            themeid = :themeid and uid = :uid ",$params);
            if (empty($row)) {
                db_insert ( t_worker, $data );
            }else{
                db_update ( t_worker, $data ,array('id' =>$row['id']));
            }

            //判断是否有设置首图海报，有则直接生成
            $fans=$data;
            $qrimg = $data ['qrcode'];
            $poster =  Poster::getByThemeIdnew($themeid,1);
            if(!empty($poster['id']) && !empty($qrimg)){
                $member = array(
                    "openid"   =>$fans['openid'],
                    'nickname' =>$fans['nickname'],
                    'avatar'   =>$fans['avatar'],
                    // 'shareurl' => $shareurl,
                    'themeid' =>$themeid,
                    'addtime' => TIMESTAMP,
                );
                $poster['bg']=str_replace("/99.jpg","/haibao.jpg",$poster['bg']);

                $img = Poster::createGoodsPoster($poster, $member, $qrimg);
                $hbimg = str_replace("http://", "https://", $img['img']) ;
                db_update(t_worker, array('poster' =>$hbimg), array( 'themeid' => $themeid, 'openid' => $fans['openid']));
            }

        }
        return $row;
    }

    //删除重复
    static function WorkerDeleteChongfu($themeid){
        if (empty($themeid)) {
            return;
        }
        $sql = "delete  FROM  " . tablename(t_worker) . "
        WHERE 1=1
            AND `uid` in (SELECT * FROM ( (SELECT `uid` `uids` FROM " . tablename(t_worker) . "  where `themeid` = {$themeid} GROUP BY uid HAVING COUNT(`uid`)>1) ) a)
            AND id not in (SELECT * FROM ( (SELECT MIN(id) ids FROM " . tablename(t_worker) . " where `themeid` = {$themeid} GROUP BY uid HAVING COUNT(`uid`)>1) ) b)
            and `themeid` = {$themeid}";

        db_query ($sql);
    }
    //获取技术信息
    static function getjishu($theme,$system,$pinpailogo='')
    {
        $jishu=array();
        if ($theme['yixuanbanquan'] != '1'){
            if (empty($theme['USERJISHU'])){
                $jishu['pinpai'] = $_G['companyname'];
                $jishu['txt']=$system['s']['yixuanjishu'];
                $jishu['mobile']=$system['s']['yixuanphone'];
            }else{
                $jishu['pinpai'] = $theme['USERCOMPANYNAME'];
                $jishu['txt']=html_entity_decode($theme['USERJISHU'], ENT_QUOTES);
                $jishu['mobile']=str_replace("tel:", "", $theme['USERURL']);
            }
        }

        if(empty($pinpailogo)){
            if ($jishu['pinpai']=='飞驰软件'){
                $pinpailogo='https://css2020.yixuan.net/2020css/yx2020/images/logo_fc.png';
            }elseif ($jishu['pinpai']=='金策软件'){
                $pinpailogo='https://css2020.yixuan.net/2020css/yx2020/images/logo_jc.png';
            }else{
                $pinpailogo='https://css2020.yixuan.net/2020css/yx2020/images/logo.png';
            }
        }
        $jishu['logo'] = $pinpailogo;
        if (!empty($theme['jubf'])){
            $jishu['pinpai'] = $theme['jubf'];
        }
        return $jishu;
    }

}
